Ext.namespace("Microtraining.Admin.Chapter");
Mt = Microtraining.Admin;
Mt.Chapter={
	/**
	 * 全局配置
	 */
	Config:{
		/**
		 *分页:每页显示记录数
		 */
		PageSize:15,
		/**
		 *显示配置
		 */
		View:{
			/**
			 * 显示章节的视图相对章节列表Grid的位置
			 * 1:上方,2:下方,3:左侧,4:右侧,
			 */
			Direction:2,
			/**
			 *是否显示。
			 */
			IsShow:0,
			/**
			 * 是否固定显示章节信息页(或者打开新窗口)
			 */
			IsFix:0
		},
    /**
     * 在线编辑器类型。
     * 1:CkEditor,2:KindEditor,3:xhEditor,4:UEditor
     * 配合Action的变量配置$online_editor
     */
    OnlineEditor:4
	},
	/**
	 * Cookie设置
	 */
	Cookie:new Ext.state.CookieProvider(),
	/**
	 * 初始化
	 */
	Init:function(){
		if (Mt.Chapter.Cookie.get('View.Direction')){
			Mt.Chapter.Config.View.Direction=Mt.Chapter.Cookie.get('View.Direction');
		}
		if (Mt.Chapter.Cookie.get('View.IsFix')!=null){
			Mt.Chapter.Config.View.IsFix=Mt.Chapter.Cookie.get('View.IsFix');
		}
    if (Ext.util.Cookies.get('OnlineEditor')!=null){
      Mt.Chapter.Config.OnlineEditor=parseInt(Ext.util.Cookies.get('OnlineEditor'));
    }

	}
};
/**
 * Model:数据模型
 */
Mt.Chapter.Store = {
  optionStore:new Ext.data.ArrayStore({
    fields : [
      {name : 'oid',type : 'string'},
      {name : 'title',type : 'string'},
      {name : 'current',type : 'int'},
    ]
  }),
	/**
	 * 章节
	 */
	chapterStore:new Ext.data.Store({
		reader: new Ext.data.JsonReader({
			totalProperty: 'totalCount',
			successProperty: 'success',
			root: 'data',remoteSort: true,
			fields : [
        {name: 'chapter_id',type: 'int'},
        {name: 'lesson_id',type: 'int'},
        {name: 'lesson_name',type: 'string'},
        {name: 'chapter_name',type: 'string'},
        {name: 'admin_name',type: 'string'},
        {name: 'content',type: 'string'},
        {name: 'contentShow',type:'string'},
        {name: 'keywords',type: 'string'},
        {name: 'isShow',type: 'string'},
        {name: 'isComment',type: 'string'},
        {name: 'isScoring',type: 'string'},
        {name: 'isUpload_file',type: 'string'},
        {name: 'isAdvertisement',type: 'string'},
        {name: 'sort_order',type: 'int'},
        {name: 'head_image',type: 'string'},
        {name: 'begin_time',type: 'date',dateFormat:'Y-m-d H:i:s'},
        {name: 'end_time',type: 'date',dateFormat:'Y-m-d H:i:s'}
			]}
		),
		writer: new Ext.data.JsonWriter({
			encode: false
		}),
		listeners : {
			beforeload : function(store, options) {
				if (Ext.isReady) {
					if (!options.params.limit)options.params.limit=Mt.Chapter.Config.PageSize;
					Ext.apply(options.params, Mt.Chapter.View.Running.chapterGrid.filter);//保证分页也将查询条件带上
				}
			}
		}
	}),
  /**
   * 企业课程
   */
  lessonStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/lesson.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'lessons',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'lesson_id'
    }, [
      {name: 'lesson_id', mapping: 'lesson_id'},
      {name: 'lesson_name', mapping: 'lesson_name'}
    ])
  }),
  /**
   * 会员附件
   */
  lattachmentStore:new Ext.data.Store({
    reader: new Ext.data.JsonReader({
      totalProperty: 'totalCount',
      successProperty: 'success',
      root: 'data',remoteSort: true,
      fields : [
        {name: 'lattachment_id',type: 'int'},
        {name: 'username',type: 'string'},
        {name: 'lesson_name',type: 'string'},
        {name: 'chapter_name',type: 'string'},
        {name: 'file_name',type: 'string'},
        {name: 'file_path',type: 'string'}
      ]}
    ),
    writer: new Ext.data.JsonWriter({
      encode: false 
    }),
    listeners : {
      beforeload : function(store, options) {
        if (Ext.isReady) {
          if (!options.params.limit)options.params.limit=Mt.Chapter.Config.PageSize;
          Ext.apply(options.params, Mt.Chapter.View.Running.lattachmentGrid.filter);//保证分页也将查询条件带上
        }
      }
    }
  }),
  /**
   * 会员
   */
  memberStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/member.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'members',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'member_id'
    }, [
      {name: 'member_id', mapping: 'member_id'},
      {name: 'username', mapping: 'username'}
    ])
  }),
  /**
   * 章节评论
   */
  lcommentStore:new Ext.data.Store({
    reader: new Ext.data.JsonReader({
      totalProperty: 'totalCount',
      successProperty: 'success',
      root: 'data',remoteSort: true,
      fields : [
        {name: 'lcomment_id',type: 'int'},
        {name: 'lesson_name',type: 'string'},
        {name: 'chapter_name',type: 'string'},
        {name: 'username',type: 'string'},
        {name: 'comment',type: 'string'}
      ]}
    ),
    writer: new Ext.data.JsonWriter({
      encode: false 
    }),
    listeners : {
      beforeload : function(store, options) {
        if (Ext.isReady) {
          if (!options.params.limit)options.params.limit=Mt.Chapter.Config.PageSize;
          Ext.apply(options.params, Mt.Chapter.View.Running.lcommentGrid.filter);//保证分页也将查询条件带上
        }
      }
    }
  }),
  /**
   * 章节评分
   */
  lratingStore:new Ext.data.Store({
    reader: new Ext.data.JsonReader({
      totalProperty: 'totalCount',
      successProperty: 'success',
      root: 'data',remoteSort: true,
      fields : [
        {name: 'lrating_id',type: 'int'},
        {name: 'lesson_name',type: 'string'},
        {name: 'chapter_name',type: 'string'},
        {name: 'username',type: 'string'},
        {name: 'rate',type: 'int'}
      ]}
    ),
    writer: new Ext.data.JsonWriter({
      encode: false 
    }),
    listeners : {
      beforeload : function(store, options) {
        if (Ext.isReady) {
          if (!options.params.limit)options.params.limit=Mt.Chapter.Config.PageSize;
          Ext.apply(options.params, Mt.Chapter.View.Running.lratingGrid.filter);//保证分页也将查询条件带上
        }
      }
    }
  }),
  /**
   * 练习题
   */
  practiceStore:new Ext.data.Store({
    reader: new Ext.data.JsonReader({
      totalProperty: 'totalCount',
      successProperty: 'success',
      root: 'data',remoteSort: true,
      fields : [
        {name: 'practice_id',type: 'int'},
        {name: 'lesson_name',type: 'string'},
        {name: 'lesson_id',type: 'int'},
        {name: 'chapter_id',type: 'int'},
        {name: 'chapter_name',type: 'string'},
        {name: 'practice_title',type: 'string'},
        {name: 'options_json',type: 'string'},
        {name: 'answer',type: 'int'},
        {name: 'point',type: 'int'},
        {name: 'sort_order',type: 'int'},
        {name: 'isShow',type: 'string'},
        {name: 'isComment',type: 'string'},
        {name: 'isScoring',type: 'string'},
        {name: 'isUpload_file',type: 'string'},
        {name: 'isAdvertisement',type: 'string'}
      ]}
    ),
    writer: new Ext.data.JsonWriter({
      encode: false 
    }),
    listeners : {
      beforeload : function(store, options) {
        if (Ext.isReady) {
          if (!options.params.limit)options.params.limit=Mt.Chapter.Config.PageSize;
          Ext.apply(options.params, Mt.Chapter.View.Running.practiceGrid.filter);//保证分页也将查询条件带上
        }
      }
    }
  })
};
/**
 * View:章节显示组件
 */
Mt.Chapter.View={
	/**
	 * 编辑窗口：新建或者修改章节
	 */
	EditWindow:Ext.extend(Ext.Window,{
		constructor : function(config) {
			config = Ext.apply({
				/**
				 * 自定义类型:保存类型
				 * 0:保存窗口,1:修改窗口
				 */
				savetype:0,
				closeAction : "hide",
				constrainHeader:true,maximizable: true,collapsible: true,
				width : 450,height : 550,minWidth : 400,minHeight : 450,
				layout : 'fit',plain : true,buttonAlign : 'center',
				defaults : {
					autoScroll : true
				},
				listeners:{
					beforehide:function(){
						this.editForm.form.getEl().dom.reset();
					},
          afterrender:function(){
            switch (Mt.Chapter.Config.OnlineEditor)
            {
                case 1:
                    ckeditor_replace_content();
                    break
                case 2:
                    Mt.Chapter.View.EditWindow.KindEditor_content = KindEditor.create('textarea[name="content"]',{width:'98%',minHeith:'350px', filterMode:true});
                    break
                case 3:
                    pageInit_content();
                    break
                default:
                    this.editForm.content.setWidth("98%");
                    pageInit_ue_content();
            }
          }
				},
				items : [
					new Ext.form.FormPanel({
						ref:'editForm',layout:'form',fileUpload: true,
						labelWidth : 100,labelAlign : "center",
						bodyStyle : 'padding:5px 5px 0',align : "center",
						api : {},
						defaults : {
							xtype : 'textfield',anchor:'98%'
						},
						items : [
              {xtype: 'hidden',name : 'chapter_id',ref:'../chapter_id'},
              {xtype: 'hidden',name : 'lesson_id',ref:'../lesson_id'},
              {xtype: 'hidden',  name : 'head_image',ref:'../head_image'},
              {
                 fieldLabel : '课程',xtype: 'combo',name : 'lesson_name',ref : '../lesson_name',
                 store:Mt.Chapter.Store.lessonStoreForCombo,emptyText: '请选择课程',itemSelector: 'div.search-item',
                 loadingText: '查询中...',width: 570, pageSize:Mt.Chapter.Config.PageSize,
                 displayField:'lesson_name',grid:this,
                 mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                 forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                 tpl:new Ext.XTemplate(
                   '<tpl for="."><div class="search-item">',
                     '<h3>{lesson_name}</h3>',
                   '</div></tpl>'
                 ),
                 listeners:{
                   'beforequery': function(event){delete event.combo.lastQuery;}
                 },
                 onSelect:function(record,index){
                   if(this.fireEvent('beforeselect', this, record, index) !== false){
                    this.grid.lesson_id.setValue(record.data.lesson_id);
                    this.grid.lesson_name.setValue(record.data.lesson_name);
                    this.collapse();
                   }
                 }
              },
              {fieldLabel : '章节名称',name : 'chapter_name'},
              {fieldLabel : '头像',name : 'head_imageUpload',ref:'../head_imageUpload',xtype:'fileuploadfield',
              emptyText: '请上传头像文件',buttonText: '',accept:'image/*',buttonCfg: {iconCls: 'upload-icon'}},
              {fieldLabel : '开始日期',ref:'../begin_time',name : 'begin_time',xtype : 'datefield',format : "Y-m-d"},
              {fieldLabel : '结束日期',ref:'../end_time',name : 'end_time',xtype : 'datefield',format : "Y-m-d"},
              {fieldLabel : '章节内容',name : 'content',xtype : 'textarea',id:'content',ref:'content'},
              // {fieldLabel : '内容关键字',name : 'keywords'},
              {fieldLabel : '是否显示',hiddenName : 'isShow'
                 ,xtype:'combo',ref:'../isShow',mode : 'local',triggerAction : 'all',
                 lazyRender : true,editable: false,allowBlank : false,valueNotFoundText:'否',
                 store : new Ext.data.SimpleStore({
                   fields : ['value', 'text'],
                   data : [['0', '否'], ['1', '是']]
                 }),emptyText: '请选择是否显示',
                 valueField : 'value',displayField : 'text'
              },
              // {fieldLabel : '是否评论',hiddenName : 'isComment'
              //    ,xtype:'combo',ref:'../isComment',mode : 'local',triggerAction : 'all',
              //    lazyRender : true,editable: false,allowBlank : false,valueNotFoundText:'否',
              //    store : new Ext.data.SimpleStore({
              //      fields : ['value', 'text'],
              //      data : [['0', '否'], ['1', '是']]
              //    }),emptyText: '请选择是否评论',
              //    valueField : 'value',displayField : 'text'
              // },
              // {fieldLabel : '是否打分',hiddenName : 'isScoring'
              //    ,xtype:'combo',ref:'../isScoring',mode : 'local',triggerAction : 'all',
              //    lazyRender : true,editable: false,allowBlank : false,valueNotFoundText:'否',
              //    store : new Ext.data.SimpleStore({
              //      fields : ['value', 'text'],
              //      data : [['0', '否'], ['1', '是']]
              //    }),emptyText: '请选择是否打分',
              //    valueField : 'value',displayField : 'text'
              // },
              // {fieldLabel : '是否上传文件',hiddenName : 'isUpload_file'
              //    ,xtype:'combo',ref:'../isUpload_file',mode : 'local',triggerAction : 'all',
              //    lazyRender : true,editable: false,allowBlank : false,valueNotFoundText:'否',
              //    store : new Ext.data.SimpleStore({
              //      fields : ['value', 'text'],
              //      data : [['0', '否'], ['1', '是']]
              //    }),emptyText: '请选择是否上传文件',
              //    valueField : 'value',displayField : 'text'
              // },
              // {fieldLabel : '是否打开广告',hiddenName : 'isAdvertisement'
              //    ,xtype:'combo',ref:'../isAdvertisement',mode : 'local',triggerAction : 'all',
              //    lazyRender : true,editable: false,allowBlank : false,valueNotFoundText:'否',
              //    store : new Ext.data.SimpleStore({
              //      fields : ['value', 'text'],
              //      data : [['0', '否'], ['1', '是']]
              //    }),emptyText: '请选择是否打开广告',
              //    valueField : 'value',displayField : 'text'
              // },
              {fieldLabel : '排序',name : 'sort_order',xtype : 'numberfield'}
						]
					})
				],
				buttons : [{
					text: "",ref : "../saveBtn",scope:this,
					handler : function() {
            switch (Mt.Chapter.Config.OnlineEditor)
            {
                case 1:
                    if (CKEDITOR.instances.content) this.editForm.content.setValue(CKEDITOR.instances.content.getData());
                    break
                case 2:
                    if (Mt.Chapter.View.EditWindow.KindEditor_content)this.editForm.content.setValue(Mt.Chapter.View.EditWindow.KindEditor_content.html());
                    break
                case 3:
                    if (xhEditor_content)this.editForm.content.setValue(xhEditor_content.getSource());
                    break
                default:
                    if (ue_content)this.editForm.content.setValue(ue_content.getContent());
            }

						if (!this.editForm.getForm().isValid()) {
							return;
						}

            var now = new Date();
            var str=now.getFullYear()+'-'+(now.getMonth()+1)+'-'+now.getDate();
            var today = new Date(str).getTime();

            var etime=this.end_time.getValue().getTime();
            var btime=this.begin_time.getValue().getTime();
            if (etime <= today) {
              Ext.Msg.alert('提示','结束时间不能小于今日');
              return;
            };
            if (etime <= btime) {
              Ext.Msg.alert('提示','结束时间不能小于开始时间');
              return;
            };

						editWindow=this;
						if (this.savetype==0){
							this.editForm.api.submit=ExtServiceChapter.save;
							this.editForm.getForm().submit({
								success : function(form, action) {
									Ext.Msg.alert("提示", "保存成功！");
									Mt.Chapter.View.Running.chapterGrid.doSelectChapter();
									form.reset();
									editWindow.hide();
								},
								failure : function(form, response) {
									Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
								}
							});
						}else{
							this.editForm.api.submit=ExtServiceChapter.update;
							this.editForm.getForm().submit({
								success : function(form, action) {
									Mt.Chapter.View.Running.chapterGrid.store.reload();
									Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
										Mt.Chapter.View.Running.chapterGrid.bottomToolbar.doRefresh();
									}});
									form.reset();
									editWindow.hide();
								},
								failure : function(form, response) {
									Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
								}
							});
						}
					}
				}, {
					text : "取 消",scope:this,
					handler : function() {
						this.hide();
					}
				}, {
					text : "重 置",ref:'../resetBtn',scope:this,
					handler : function() {
						this.editForm.form.loadRecord(Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected());
            this.head_imageUpload.setValue(this.head_image.getValue());
            switch (Mt.Chapter.Config.OnlineEditor)
            {
                case 1:
                    if (CKEDITOR.instances.content) CKEDITOR.instances.content.setData(Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.content);
                    break
                case 2:
                    if (Mt.Chapter.View.EditWindow.KindEditor_content) Mt.Chapter.View.EditWindow.KindEditor_content.html(Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.content);
                    break
                case 3:
                    if (xhEditor_content) xhEditor_content.setSource(Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.content);
                    break
                default:
                    if (ue_content) ue_content.setContent(Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.content);
            }
					}
				}]
			}, config);
			Mt.Chapter.View.EditWindow.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 显示章节详情
	 */
	ChapterView:{
		/**
		 * Tab页：容器包含显示与章节所有相关的信息
		 */
		Tabs:Ext.extend(Ext.TabPanel,{
			constructor : function(config) {
				config = Ext.apply({
					region : 'south',collapseMode : 'mini',split : true,
					activeTab: 1, tabPosition:"bottom",resizeTabs : true,
					header:false,enableTabScroll : true,tabWidth:'auto', margins : '0 3 3 0',
					defaults : {
						autoScroll : true,
						layout:'fit'
					},
					listeners:{
						beforetabchange:function(tabs,newtab,currentTab){
							if (tabs.tabFix==newtab){
								if (Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected()==null){
									Ext.Msg.alert('提示', '请先选择章节！');
									return false;
								}
								Mt.Chapter.Config.View.IsShow=1;
								Mt.Chapter.View.Running.chapterGrid.showChapter();
								Mt.Chapter.View.Running.chapterGrid.tvpView.menu.mBind.setChecked(false);
								return false;
							}
						}
					},
					items: [
						{title:'+',tabTip:'取消固定',ref:'tabFix',iconCls:'icon-fix'}
					]
				}, config);
				Mt.Chapter.View.ChapterView.Tabs.superclass.constructor.call(this, config);
        Mt.Chapter.View.Running.lattachmentGrid=new Mt.Chapter.View.LattachmentView.Grid();
        Mt.Chapter.View.Running.lcommentGrid=new Mt.Chapter.View.LcommentView.Grid();
        Mt.Chapter.View.Running.lratingGrid=new Mt.Chapter.View.LratingView.Grid();
        Mt.Chapter.View.Running.practiceGrid=new Mt.Chapter.View.PracticeView.Grid();
				this.onAddItems();
			},
			/**
			 * 根据布局调整Tabs的宽度或者高度以及折叠
			 */
			enableCollapse:function(){
				if ((Mt.Chapter.Config.View.Direction==1)||(Mt.Chapter.Config.View.Direction==2)){
					this.width =Ext.getBody().getViewSize().width;
					this.height=Ext.getBody().getViewSize().height/2;
				}else{
					this.width =Ext.getBody().getViewSize().width/2;
					this.height=Ext.getBody().getViewSize().height;
				}
				this.ownerCt.setSize(this.width,this.height);
				if (this.ownerCt.collapsed)this.ownerCt.expand();
				this.ownerCt.collapsed=false;
			},
			onAddItems:function(){
				this.add(
					{title: '基本信息',ref:'tabChapterDetail',iconCls:'tabs',
					 tpl: [
						 '<table class="viewdoblock">',
             '  <tr class="entry"><td class="head">所属用户</td><td class="content">{admin_name}</td></tr>',
             '  <tr class="entry"><td class="head">课程</td><td class="content">{lesson_name}</td></tr>',
             '  <tr class="entry"><td class="head">章节名称</td><td class="content">{chapter_name}</td></tr>',
             '  <tr class="entry"><td class="head">图标路径</td><td class="content">{head_image}</td></tr>',
             '  <tr class="entry"><td class="head">图标</td><td class="content"><tpl if="head_image"><a href="upload/images/{head_image}" target="_blank"><img width="50px" height="50px" src="upload/images/{head_image}" /></a></tpl></td></tr>', 
             '  <tr class="entry"><td class="head">章节内容</td><td class="content">{contentShow}</td></tr>',
             // '  <tr class="entry"><td class="head">内容关键字</td><td class="content">{keywords}</td></tr>',
             '  <tr class="entry"><td class="head">是否显示</td><td class="content"><tpl if="isShow == true">是</tpl><tpl if="isShow == false">否</tpl></td></tr>',
             '  <tr class="entry"><td class="head">是否评论</td><td class="content"><tpl if="isComment == true">是</tpl><tpl if="isComment == false">否</tpl></td></tr>',
             '  <tr class="entry"><td class="head">是否打分</td><td class="content"><tpl if="isScoring == true">是</tpl><tpl if="isScoring == false">否</tpl></td></tr>',
             '  <tr class="entry"><td class="head">是否上传文件</td><td class="content"><tpl if="isUpload_file == true">是</tpl><tpl if="isUpload_file == false">否</tpl></td></tr>',
             '  <tr class="entry"><td class="head">是否打开广告</td><td class="content"><tpl if="isAdvertisement == true">是</tpl><tpl if="isAdvertisement == false">否</tpl></td></tr>',
             '  <tr class="entry"><td class="head">排序</td><td class="content">{sort_order}</td></tr>',
						 '</table>'
					 ]}
				);
        this.add(
          {title: '会员附件',iconCls:'tabs',tabWidth:150,
           items:[Mt.Chapter.View.Running.lattachmentGrid]
          },
          {title: '会员评论',iconCls:'tabs',tabWidth:150,
           items:[Mt.Chapter.View.Running.lcommentGrid]
          },
          {title: '会员评分',iconCls:'tabs',tabWidth:150,
           items:[Mt.Chapter.View.Running.lratingGrid]
          },
          {title: '练习题',iconCls:'tabs',tabWidth:150,
           items:[Mt.Chapter.View.Running.practiceGrid]
          }
        );
			}
		}),
		/**
		 * 窗口:显示章节信息
		 */
		Window:Ext.extend(Ext.Window,{
			constructor : function(config) {
				config = Ext.apply({
					title:"查看章节",constrainHeader:true,maximizable: true,minimizable : true,
					width : 705,height : 500,minWidth : 450,minHeight : 400,
					layout : 'fit',resizable:true,plain : true,bodyStyle : 'padding:5px;',
					closeAction : "hide",
					items:[new Mt.Chapter.View.ChapterView.Tabs({ref:'winTabs',tabPosition:'top'})],
					listeners: {
						minimize:function(w){
							w.hide();
							Mt.Chapter.Config.View.IsShow=0;
							Mt.Chapter.View.Running.chapterGrid.tvpView.menu.mBind.setChecked(true);
						},
						hide:function(w){
							Mt.Chapter.View.Running.chapterGrid.tvpView.toggle(false);
						}
					},
					buttons: [{
						text: '新增章节',scope:this,
						handler : function() {this.hide();Mt.Chapter.View.Running.chapterGrid.addChapter();}
					},{
						text: '修改章节',scope:this,
						handler : function() {this.hide();Mt.Chapter.View.Running.chapterGrid.updateChapter();}
					}]
				}, config);
				Mt.Chapter.View.ChapterView.Window.superclass.constructor.call(this, config);
			}
		})
	},
	/**
	 * 视图：会员附件列表
	 */
	LattachmentView:{
		/**
		 *  当前创建的会员附件编辑窗口
		 */
		edit_window:null,
		/**
		 * 编辑窗口：新建或者修改会员附件
		 */
		EditWindow:Ext.extend(Ext.Window,{
			constructor : function(config) {
				config = Ext.apply({
					/**
					 * 自定义类型:保存类型
					 * 0:保存窗口,1:修改窗口
					 */
					savetype:0,closeAction : "hide",constrainHeader:true,maximizable: true,collapsible: true,
					width : 450,height : 550,minWidth : 400,minHeight : 450,
					layout : 'fit',plain : true,buttonAlign : 'center',
					defaults : {autoScroll : true},
					listeners:{
						beforehide:function(){
							this.editForm.form.getEl().dom.reset();
						}
					},
					items : [
						new Ext.form.FormPanel({
							ref:'editForm',layout:'form',
							labelWidth : 100,labelAlign : "center",
							bodyStyle : 'padding:5px 5px 0',align : "center",
							api : {},
							defaults : {
								xtype : 'textfield',anchor:'98%'
							},
							items : [
                {xtype: 'hidden',name : 'lattachment_id',ref:'../lattachment_id'},
                {xtype: 'hidden',name : 'member_id',ref:'../member_id'},
                {
                   fieldLabel : '用户',xtype: 'combo',name : 'username',ref : '../username',
                   store:Mt.Chapter.Store.memberStoreForCombo,emptyText: '请选择用户',itemSelector: 'div.search-item',
                   loadingText: '查询中...',width: 570, pageSize:Mt.Chapter.Config.PageSize,
                   displayField:'username',grid:this,
                   mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                     '<tpl for="."><div class="search-item">',
                       '<h3>{username}</h3>',
                     '</div></tpl>'
                   ),
                   listeners:{
                     'beforequery': function(event){delete event.combo.lastQuery;}
                   },
                   onSelect:function(record,index){
                     if(this.fireEvent('beforeselect', this, record, index) !== false){
                      this.grid.member_id.setValue(record.data.member_id);
                      this.grid.username.setValue(record.data.username);
                      this.collapse();
                     }
                   }
                },
                {xtype: 'hidden',name : 'lesson_id',ref:'../lesson_id'},
                {
                   fieldLabel : '课程',xtype: 'combo',name : 'lesson_name',ref : '../lesson_name',
                   store:Mt.Chapter.Store.lessonStoreForCombo,emptyText: '请选择课程',itemSelector: 'div.search-item',
                   loadingText: '查询中...',width: 570, pageSize:Mt.Chapter.Config.PageSize,
                   displayField:'lesson_name',grid:this,
                   mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                     '<tpl for="."><div class="search-item">',
                       '<h3>{lesson_name}</h3>',
                     '</div></tpl>'
                   ),
                   listeners:{
                     'beforequery': function(event){delete event.combo.lastQuery;}
                   },
                   onSelect:function(record,index){
                     if(this.fireEvent('beforeselect', this, record, index) !== false){
                      this.grid.lesson_id.setValue(record.data.lesson_id);
                      this.grid.lesson_name.setValue(record.data.lesson_name);
                      this.collapse();
                     }
                   }
                },
                {xtype: 'hidden',name : 'chapter_id',ref:'../chapter_id'},
                {fieldLabel : '名称',name : 'file_name'},
                {fieldLabel : '保存路径',name : 'file_path'}
							]
						})
					],
					buttons : [{
						text: "",ref : "../saveBtn",scope:this,
						handler : function() {

							if (!this.editForm.getForm().isValid()) {
								return;
							}
							editWindow=this;
							if (this.savetype==0){
								this.editForm.api.submit=ExtServiceLattachment.save;
								this.editForm.getForm().submit({
									success : function(form, action) {
										Ext.Msg.alert("提示", "保存成功！");
										Mt.Chapter.View.Running.lattachmentGrid.doSelectLattachment();
										form.reset();
										editWindow.hide();
									},
									failure : function(form, response) {
										Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
									}
								});
							}else{
								this.editForm.api.submit=ExtServiceLattachment.update;
								this.editForm.getForm().submit({
									success : function(form, action) {
										Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
											Mt.Chapter.View.Running.lattachmentGrid.bottomToolbar.doRefresh();
										}});
										form.reset();
										editWindow.hide();
									},
									failure : function(form, response) {
										Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
									}
								});
							}
						}
					}, {
						text : "取 消",scope:this,
						handler : function() {
							this.hide();
						}
					}, {
						text : "重 置",ref:'../resetBtn',scope:this,
						handler : function() {
							this.editForm.form.loadRecord(Mt.Chapter.View.Running.lattachmentGrid.getSelectionModel().getSelected());

						}
					}]
				}, config);
				Mt.Chapter.View.LattachmentView.EditWindow.superclass.constructor.call(this, config);
			}
		}),
		/**
		 * 查询条件
		 */
		filter:null,
		/**
		 * 视图：会员附件列表
		 */
		Grid:Ext.extend(Ext.grid.GridPanel, {
			constructor : function(config) {
				config = Ext.apply({
					store : Mt.Chapter.Store.lattachmentStore,sm : this.sm,
					frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
					loadMask : true,stripeRows : true,headerAsText : false,
					defaults : {autoScroll : true},
					cm : new Ext.grid.ColumnModel({
						defaults:{
							width:120,sortable : true
						},
						columns : [
              this.sm,
              {header : '标识',dataIndex : 'lattachment_id',hidden:true},
              {header : '用户',dataIndex : 'username'},
              {header : '附件名称',dataIndex : 'file_name'}
              // {header : '保存路径',dataIndex : 'file_path'}
						]
					}),
					tbar : {
						xtype : 'container',layout : 'anchor',
						height : 27,style:'font-size:14px',
						defaults : {
							height : 27,anchor : '100%'
						},
						items : [
							new Ext.Toolbar({
								defaults:{
								  scope: this
								},
								items : [
									{
										text: '反选',iconCls : 'icon-reverse',
										handler: function(){
											this.onReverseSelect();
										}
									},/*'-',{
										text : '添加会员附件',iconCls : 'icon-add',
										handler : function() {
											this.addLattachment();
										}
									},'-',{
										text : '修改会员附件',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
										handler : function() {
											this.updateLattachment();
										}
									},*/'-',{
										text : '删除会员附件', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
										handler : function() {
											this.deleteLattachment();
										}
									},'-']}
						)]
					},
					bbar: new Ext.PagingToolbar({
						pageSize: Mt.Chapter.Config.PageSize,
						store: Mt.Chapter.Store.lattachmentStore,scope:this,autoShow:true,displayInfo: true,
						displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',emptyMsg: "无显示数据",
						items: [
							{xtype:'label', text: '每页显示'},
							{xtype:'numberfield', value:Mt.Chapter.Config.PageSize,minValue:1,width:35,style:'text-align:center',allowBlank: false,
								listeners:
								{
									change:function(Field, newValue, oldValue){
										var num = parseInt(newValue);
										if (isNaN(num) || !num || num<1)
										{
											num = Mt.Chapter.Config.PageSize;
											Field.setValue(num);
										}
										this.ownerCt.pageSize= num;
										Mt.Chapter.Config.PageSize = num;
										this.ownerCt.ownerCt.doSelectLattachment();
									},
									specialKey :function(field,e){
										if (e.getKey() == Ext.EventObject.ENTER){
											var num = parseInt(field.getValue());
											if (isNaN(num) || !num || num<1)num = Mt.Chapter.Config.PageSize;
											this.ownerCt.pageSize= num;
											Mt.Chapter.Config.PageSize = num;
											this.ownerCt.ownerCt.doSelectLattachment();
										}
									}
								}
							},{xtype:'label', text: '个'}
						]
					})
				}, config);
				/**
				 * 会员附件数据模型获取数据Direct调用
				 */
				Mt.Chapter.Store.lattachmentStore.proxy=new Ext.data.DirectProxy({
					api: {read:ExtServiceLattachment.queryPageLattachment}
				});
				Mt.Chapter.View.LattachmentView.Grid.superclass.constructor.call(this, config);
			},
			/**
			 * 行选择器
			 */
			sm : new Ext.grid.CheckboxSelectionModel({
				listeners : {
					selectionchange:function(sm) {
						// 判断删除和更新按钮是否可以激活
						this.grid.btnRemove.setDisabled(sm.getCount() < 1);
						// this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
					}
				}
			}),
			/**
			 * 查询符合条件的会员附件
			 */
			doSelectLattachment : function() {
				if (Mt.Chapter.View.Running.chapterGrid&&Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected()){
					var chapter_id = Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.chapter_id;
					var condition = {'chapter_id':chapter_id,'start':0,'limit':Mt.Chapter.Config.PageSize};
					this.filter     ={'chapter_id':chapter_id};
					ExtServiceLattachment.queryPageLattachment(condition,function(provider, response) {
						if (response.result){
							if (response.result.data) {
								var result       = new Array();
								result['data']     =response.result.data;
								result['totalCount'] =response.result.totalCount;
								Mt.Chapter.Store.lattachmentStore.loadData(result);
							} else {
								Mt.Chapter.Store.lattachmentStore.removeAll();
								Ext.Msg.alert('提示', '无符合条件的会员附件！');
							}

							if (Mt.Chapter.Store.lattachmentStore.getTotalCount()>Mt.Chapter.Config.PageSize){
								 Mt.Chapter.View.Running.lattachmentGrid.bottomToolbar.show();
							}else{
								 Mt.Chapter.View.Running.lattachmentGrid.bottomToolbar.hide();
							}
							Mt.Chapter.View.Running.chapterGrid.ownerCt.doLayout();
						}
					});
				}
			},
			/**
			 * 反选
			 */
			onReverseSelect:function() {
				for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
					if (this.sm.isSelected(i)) {
						this.sm.deselectRow(i);
					}else {
						this.sm.selectRow(i, true);
					}
				}
			},
			/**
			 * 新建会员附件
			 */
			addLattachment : function(){
				if (Mt.Chapter.View.LattachmentView.edit_window==null){
					Mt.Chapter.View.LattachmentView.edit_window=new Mt.Chapter.View.LattachmentView.EditWindow();
				}
				Mt.Chapter.View.LattachmentView.edit_window.resetBtn.setVisible(false);
				Mt.Chapter.View.LattachmentView.edit_window.saveBtn.setText('保 存');
				Mt.Chapter.View.LattachmentView.edit_window.setTitle('添加会员附件');
				Mt.Chapter.View.LattachmentView.edit_window.savetype=0;
				Mt.Chapter.View.LattachmentView.edit_window.lattachment_id.setValue("");
				var company_id = Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.chapter_id;
				Mt.Chapter.View.LattachmentView.edit_window.chapter_id.setValue(company_id);

				Mt.Chapter.View.LattachmentView.edit_window.show();
				Mt.Chapter.View.LattachmentView.edit_window.maximize();
			},
			/**
			 * 编辑会员附件时先获得选中的会员附件信息
			 */
			updateLattachment : function() {
				if (Mt.Chapter.View.LattachmentView.edit_window==null){
					Mt.Chapter.View.LattachmentView.edit_window=new Mt.Chapter.View.LattachmentView.EditWindow();
				}
				Mt.Chapter.View.LattachmentView.edit_window.saveBtn.setText('修 改');
				Mt.Chapter.View.LattachmentView.edit_window.resetBtn.setVisible(true);
				Mt.Chapter.View.LattachmentView.edit_window.setTitle('修改会员附件');
				Mt.Chapter.View.LattachmentView.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
				Mt.Chapter.View.LattachmentView.edit_window.savetype=1;

				Mt.Chapter.View.LattachmentView.edit_window.show();
				Mt.Chapter.View.LattachmentView.edit_window.maximize();
			},
			/**
			 * 删除会员附件
			 */
			deleteLattachment : function() {
				Ext.Msg.confirm('提示', '确实要删除所选的会员附件吗?', this.confirmDeleteLattachment,this);
			},
			/**
			 * 确认删除会员附件
			 */
			confirmDeleteLattachment : function(btn) {
				if (btn == 'yes') {
					var del_lattachment_ids ="";
					var selectedRows  = this.getSelectionModel().getSelections();
					for ( var flag = 0; flag < selectedRows.length; flag++) {
						del_lattachment_ids=del_lattachment_ids+selectedRows[flag].data.lattachment_id+",";
					}
					ExtServiceLattachment.deleteByIds(del_lattachment_ids);
					this.doSelectLattachment();
					Ext.Msg.alert("提示", "删除成功！");
				}
			}
		})
	},
	/**
	 * 视图：章节评论列表
	 */
	LcommentView:{
		/**
		 *  当前创建的章节评论编辑窗口
		 */
		edit_window:null,
		/**
		 * 编辑窗口：新建或者修改章节评论
		 */
		EditWindow:Ext.extend(Ext.Window,{
			constructor : function(config) {
				config = Ext.apply({
					/**
					 * 自定义类型:保存类型
					 * 0:保存窗口,1:修改窗口
					 */
					savetype:0,closeAction : "hide",constrainHeader:true,maximizable: true,collapsible: true,
					width : 450,height : 550,minWidth : 400,minHeight : 450,
					layout : 'fit',plain : true,buttonAlign : 'center',
					defaults : {autoScroll : true},
					listeners:{
						beforehide:function(){
							this.editForm.form.getEl().dom.reset();
						}
					},
					items : [
						new Ext.form.FormPanel({
							ref:'editForm',layout:'form',
							labelWidth : 100,labelAlign : "center",
							bodyStyle : 'padding:5px 5px 0',align : "center",
							api : {},
							defaults : {
								xtype : 'textfield',anchor:'98%'
							},
							items : [
                {xtype: 'hidden',name : 'lcomment_id',ref:'../lcomment_id'},
                {xtype: 'hidden',name : 'lesson_id',ref:'../lesson_id'},
                {
                   fieldLabel : '课程',xtype: 'combo',name : 'lesson_name',ref : '../lesson_name',
                   store:Mt.Chapter.Store.lessonStoreForCombo,emptyText: '请选择课程',itemSelector: 'div.search-item',
                   loadingText: '查询中...',width: 570, pageSize:Mt.Chapter.Config.PageSize,
                   displayField:'lesson_name',grid:this,
                   mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                     '<tpl for="."><div class="search-item">',
                       '<h3>{lesson_name}</h3>',
                     '</div></tpl>'
                   ),
                   listeners:{
                     'beforequery': function(event){delete event.combo.lastQuery;}
                   },
                   onSelect:function(record,index){
                     if(this.fireEvent('beforeselect', this, record, index) !== false){
                      this.grid.lesson_id.setValue(record.data.lesson_id);
                      this.grid.lesson_name.setValue(record.data.lesson_name);
                      this.collapse();
                     }
                   }
                },
                {xtype: 'hidden',name : 'chapter_id',ref:'../chapter_id'},
                {xtype: 'hidden',name : 'member_id',ref:'../member_id'},
                {
                   fieldLabel : '用户',xtype: 'combo',name : 'username',ref : '../username',
                   store:Mt.Chapter.Store.memberStoreForCombo,emptyText: '请选择用户',itemSelector: 'div.search-item',
                   loadingText: '查询中...',width: 570, pageSize:Mt.Chapter.Config.PageSize,
                   displayField:'username',grid:this,
                   mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                     '<tpl for="."><div class="search-item">',
                       '<h3>{username}</h3>',
                     '</div></tpl>'
                   ),
                   listeners:{
                     'beforequery': function(event){delete event.combo.lastQuery;}
                   },
                   onSelect:function(record,index){
                     if(this.fireEvent('beforeselect', this, record, index) !== false){
                      this.grid.member_id.setValue(record.data.member_id);
                      this.grid.username.setValue(record.data.username);
                      this.collapse();
                     }
                   }
                },
                {fieldLabel : '评论',name : 'comment'}
							]
						})
					],
					buttons : [{
						text: "",ref : "../saveBtn",scope:this,
						handler : function() {

							if (!this.editForm.getForm().isValid()) {
								return;
							}
							editWindow=this;
							if (this.savetype==0){
								this.editForm.api.submit=ExtServiceLcomment.save;
								this.editForm.getForm().submit({
									success : function(form, action) {
										Ext.Msg.alert("提示", "保存成功！");
										Mt.Chapter.View.Running.lcommentGrid.doSelectLcomment();
										form.reset();
										editWindow.hide();
									},
									failure : function(form, response) {
										Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
									}
								});
							}else{
								this.editForm.api.submit=ExtServiceLcomment.update;
								this.editForm.getForm().submit({
									success : function(form, action) {
										Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
											Mt.Chapter.View.Running.lcommentGrid.bottomToolbar.doRefresh();
										}});
										form.reset();
										editWindow.hide();
									},
									failure : function(form, response) {
										Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
									}
								});
							}
						}
					}, {
						text : "取 消",scope:this,
						handler : function() {
							this.hide();
						}
					}, {
						text : "重 置",ref:'../resetBtn',scope:this,
						handler : function() {
							this.editForm.form.loadRecord(Mt.Chapter.View.Running.lcommentGrid.getSelectionModel().getSelected());

						}
					}]
				}, config);
				Mt.Chapter.View.LcommentView.EditWindow.superclass.constructor.call(this, config);
			}
		}),
		/**
		 * 查询条件
		 */
		filter:null,
		/**
		 * 视图：章节评论列表
		 */
		Grid:Ext.extend(Ext.grid.GridPanel, {
			constructor : function(config) {
				config = Ext.apply({
					store : Mt.Chapter.Store.lcommentStore,sm : this.sm,
					frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
					loadMask : true,stripeRows : true,headerAsText : false,
					defaults : {autoScroll : true},
					cm : new Ext.grid.ColumnModel({
						defaults:{
							width:120,sortable : true
						},
						columns : [
              this.sm,
              {header : '标识',dataIndex : 'lcomment_id',hidden:true},
              {header : '课程',dataIndex : 'lesson_name'},
              {header : '用户',dataIndex : 'username'},
              {header : '评论',dataIndex : 'comment'}
						]
					}),
					tbar : {
						xtype : 'container',layout : 'anchor',
						height : 27,style:'font-size:14px',
						defaults : {
							height : 27,anchor : '100%'
						},
						items : [
							new Ext.Toolbar({
								defaults:{
								  scope: this
								},
								items : [
									{
										text: '反选',iconCls : 'icon-reverse',
										handler: function(){
											this.onReverseSelect();
										}
									},'-',/*{
										text : '添加章节评论',iconCls : 'icon-add',
										handler : function() {
											this.addLcomment();
										}
									},'-',{
										text : '修改章节评论',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
										handler : function() {
											this.updateLcomment();
										}
									},'-',*/{
										text : '删除章节评论', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
										handler : function() {
											this.deleteLcomment();
										}
									},'-']}
						)]
					},
					bbar: new Ext.PagingToolbar({
						pageSize: Mt.Chapter.Config.PageSize,
						store: Mt.Chapter.Store.lcommentStore,scope:this,autoShow:true,displayInfo: true,
						displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',emptyMsg: "无显示数据",
						items: [
							{xtype:'label', text: '每页显示'},
							{xtype:'numberfield', value:Mt.Chapter.Config.PageSize,minValue:1,width:35,style:'text-align:center',allowBlank: false,
								listeners:
								{
									change:function(Field, newValue, oldValue){
										var num = parseInt(newValue);
										if (isNaN(num) || !num || num<1)
										{
											num = Mt.Chapter.Config.PageSize;
											Field.setValue(num);
										}
										this.ownerCt.pageSize= num;
										Mt.Chapter.Config.PageSize = num;
										this.ownerCt.ownerCt.doSelectLcomment();
									},
									specialKey :function(field,e){
										if (e.getKey() == Ext.EventObject.ENTER){
											var num = parseInt(field.getValue());
											if (isNaN(num) || !num || num<1)num = Mt.Chapter.Config.PageSize;
											this.ownerCt.pageSize= num;
											Mt.Chapter.Config.PageSize = num;
											this.ownerCt.ownerCt.doSelectLcomment();
										}
									}
								}
							},{xtype:'label', text: '个'}
						]
					})
				}, config);
				/**
				 * 章节评论数据模型获取数据Direct调用
				 */
				Mt.Chapter.Store.lcommentStore.proxy=new Ext.data.DirectProxy({
					api: {read:ExtServiceLcomment.queryPageLcomment}
				});
				Mt.Chapter.View.LcommentView.Grid.superclass.constructor.call(this, config);
			},
			/**
			 * 行选择器
			 */
			sm : new Ext.grid.CheckboxSelectionModel({
				listeners : {
					selectionchange:function(sm) {
						// 判断删除和更新按钮是否可以激活
						this.grid.btnRemove.setDisabled(sm.getCount() < 1);
						// this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
					}
				}
			}),
			/**
			 * 查询符合条件的章节评论
			 */
			doSelectLcomment : function() {
				if (Mt.Chapter.View.Running.chapterGrid&&Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected()){
					var chapter_id = Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.chapter_id;
					var condition = {'chapter_id':chapter_id,'start':0,'limit':Mt.Chapter.Config.PageSize};
					this.filter     ={'chapter_id':chapter_id};
					ExtServiceLcomment.queryPageLcomment(condition,function(provider, response) {
						if (response.result){
							if (response.result.data) {
								var result       = new Array();
								result['data']     =response.result.data;
								result['totalCount'] =response.result.totalCount;
								Mt.Chapter.Store.lcommentStore.loadData(result);
							} else {
								Mt.Chapter.Store.lcommentStore.removeAll();
								Ext.Msg.alert('提示', '无符合条件的章节评论！');
							}

							if (Mt.Chapter.Store.lcommentStore.getTotalCount()>Mt.Chapter.Config.PageSize){
								 Mt.Chapter.View.Running.lcommentGrid.bottomToolbar.show();
							}else{
								 Mt.Chapter.View.Running.lcommentGrid.bottomToolbar.hide();
							}
							Mt.Chapter.View.Running.chapterGrid.ownerCt.doLayout();
						}
					});
				}
			},
			/**
			 * 反选
			 */
			onReverseSelect:function() {
				for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
					if (this.sm.isSelected(i)) {
						this.sm.deselectRow(i);
					}else {
						this.sm.selectRow(i, true);
					}
				}
			},
			/**
			 * 新建章节评论
			 */
			addLcomment : function(){
				if (Mt.Chapter.View.LcommentView.edit_window==null){
					Mt.Chapter.View.LcommentView.edit_window=new Mt.Chapter.View.LcommentView.EditWindow();
				}
				Mt.Chapter.View.LcommentView.edit_window.resetBtn.setVisible(false);
				Mt.Chapter.View.LcommentView.edit_window.saveBtn.setText('保 存');
				Mt.Chapter.View.LcommentView.edit_window.setTitle('添加章节评论');
				Mt.Chapter.View.LcommentView.edit_window.savetype=0;
				Mt.Chapter.View.LcommentView.edit_window.lcomment_id.setValue("");
				var company_id = Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.chapter_id;
				Mt.Chapter.View.LcommentView.edit_window.chapter_id.setValue(company_id);

				Mt.Chapter.View.LcommentView.edit_window.show();
				Mt.Chapter.View.LcommentView.edit_window.maximize();
			},
			/**
			 * 编辑章节评论时先获得选中的章节评论信息
			 */
			updateLcomment : function() {
				if (Mt.Chapter.View.LcommentView.edit_window==null){
					Mt.Chapter.View.LcommentView.edit_window=new Mt.Chapter.View.LcommentView.EditWindow();
				}
				Mt.Chapter.View.LcommentView.edit_window.saveBtn.setText('修 改');
				Mt.Chapter.View.LcommentView.edit_window.resetBtn.setVisible(true);
				Mt.Chapter.View.LcommentView.edit_window.setTitle('修改章节评论');
				Mt.Chapter.View.LcommentView.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
				Mt.Chapter.View.LcommentView.edit_window.savetype=1;

				Mt.Chapter.View.LcommentView.edit_window.show();
				Mt.Chapter.View.LcommentView.edit_window.maximize();
			},
			/**
			 * 删除章节评论
			 */
			deleteLcomment : function() {
				Ext.Msg.confirm('提示', '确实要删除所选的章节评论吗?', this.confirmDeleteLcomment,this);
			},
			/**
			 * 确认删除章节评论
			 */
			confirmDeleteLcomment : function(btn) {
				if (btn == 'yes') {
					var del_lcomment_ids ="";
					var selectedRows  = this.getSelectionModel().getSelections();
					for ( var flag = 0; flag < selectedRows.length; flag++) {
						del_lcomment_ids=del_lcomment_ids+selectedRows[flag].data.lcomment_id+",";
					}
					ExtServiceLcomment.deleteByIds(del_lcomment_ids);
					this.doSelectLcomment();
					Ext.Msg.alert("提示", "删除成功！");
				}
			}
		})
	},
	/**
	 * 视图：章节评分列表
	 */
	LratingView:{
		/**
		 *  当前创建的章节评分编辑窗口
		 */
		edit_window:null,
		/**
		 * 编辑窗口：新建或者修改章节评分
		 */
		EditWindow:Ext.extend(Ext.Window,{
			constructor : function(config) {
				config = Ext.apply({
					/**
					 * 自定义类型:保存类型
					 * 0:保存窗口,1:修改窗口
					 */
					savetype:0,closeAction : "hide",constrainHeader:true,maximizable: true,collapsible: true,
					width : 450,height : 550,minWidth : 400,minHeight : 450,
					layout : 'fit',plain : true,buttonAlign : 'center',
					defaults : {autoScroll : true},
					listeners:{
						beforehide:function(){
							this.editForm.form.getEl().dom.reset();
						}
					},
					items : [
						new Ext.form.FormPanel({
							ref:'editForm',layout:'form',
							labelWidth : 100,labelAlign : "center",
							bodyStyle : 'padding:5px 5px 0',align : "center",
							api : {},
							defaults : {
								xtype : 'textfield',anchor:'98%'
							},
							items : [
                {xtype: 'hidden',name : 'lrating_id',ref:'../lrating_id'},
                {xtype: 'hidden',name : 'lesson_id',ref:'../lesson_id'},
                {
                   fieldLabel : '课程',xtype: 'combo',name : 'lesson_name',ref : '../lesson_name',
                   store:Mt.Chapter.Store.lessonStoreForCombo,emptyText: '请选择课程',itemSelector: 'div.search-item',
                   loadingText: '查询中...',width: 570, pageSize:Mt.Chapter.Config.PageSize,
                   displayField:'lesson_name',grid:this,
                   mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                     '<tpl for="."><div class="search-item">',
                       '<h3>{lesson_name}</h3>',
                     '</div></tpl>'
                   ),
                   listeners:{
                     'beforequery': function(event){delete event.combo.lastQuery;}
                   },
                   onSelect:function(record,index){
                     if(this.fireEvent('beforeselect', this, record, index) !== false){
                      this.grid.lesson_id.setValue(record.data.lesson_id);
                      this.grid.lesson_name.setValue(record.data.lesson_name);
                      this.collapse();
                     }
                   }
                },
                {xtype: 'hidden',name : 'chapter_id',ref:'../chapter_id'},
                {xtype: 'hidden',name : 'member_id',ref:'../member_id'},
                {
                   fieldLabel : '用户',xtype: 'combo',name : 'username',ref : '../username',
                   store:Mt.Chapter.Store.memberStoreForCombo,emptyText: '请选择用户',itemSelector: 'div.search-item',
                   loadingText: '查询中...',width: 570, pageSize:Mt.Chapter.Config.PageSize,
                   displayField:'username',grid:this,
                   mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                     '<tpl for="."><div class="search-item">',
                       '<h3>{username}</h3>',
                     '</div></tpl>'
                   ),
                   listeners:{
                     'beforequery': function(event){delete event.combo.lastQuery;}
                   },
                   onSelect:function(record,index){
                     if(this.fireEvent('beforeselect', this, record, index) !== false){
                      this.grid.member_id.setValue(record.data.member_id);
                      this.grid.username.setValue(record.data.username);
                      this.collapse();
                     }
                   }
                },
                {fieldLabel : '评分',name : 'rate',xtype : 'numberfield'}
							]
						})
					],
					buttons : [{
						text: "",ref : "../saveBtn",scope:this,
						handler : function() {

							if (!this.editForm.getForm().isValid()) {
								return;
							}
							editWindow=this;
							if (this.savetype==0){
								this.editForm.api.submit=ExtServiceLrating.save;
								this.editForm.getForm().submit({
									success : function(form, action) {
										Ext.Msg.alert("提示", "保存成功！");
										Mt.Chapter.View.Running.lratingGrid.doSelectLrating();
										form.reset();
										editWindow.hide();
									},
									failure : function(form, response) {
										Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
									}
								});
							}else{
								this.editForm.api.submit=ExtServiceLrating.update;
								this.editForm.getForm().submit({
									success : function(form, action) {
										Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
											Mt.Chapter.View.Running.lratingGrid.bottomToolbar.doRefresh();
										}});
										form.reset();
										editWindow.hide();
									},
									failure : function(form, response) {
										Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
									}
								});
							}
						}
					}, {
						text : "取 消",scope:this,
						handler : function() {
							this.hide();
						}
					}, {
						text : "重 置",ref:'../resetBtn',scope:this,
						handler : function() {
							this.editForm.form.loadRecord(Mt.Chapter.View.Running.lratingGrid.getSelectionModel().getSelected());

						}
					}]
				}, config);
				Mt.Chapter.View.LratingView.EditWindow.superclass.constructor.call(this, config);
			}
		}),
		/**
		 * 查询条件
		 */
		filter:null,
		/**
		 * 视图：章节评分列表
		 */
		Grid:Ext.extend(Ext.grid.GridPanel, {
			constructor : function(config) {
				config = Ext.apply({
					store : Mt.Chapter.Store.lratingStore,sm : this.sm,
					frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
					loadMask : true,stripeRows : true,headerAsText : false,
					defaults : {autoScroll : true},
					cm : new Ext.grid.ColumnModel({
						defaults:{
							width:120,sortable : true
						},
						columns : [
              this.sm,
              {header : '标识',dataIndex : 'lrating_id',hidden:true},
              {header : '课程',dataIndex : 'lesson_name'},
              {header : '用户',dataIndex : 'username'},
              {header : '评分',dataIndex : 'rate'}
						]
					}),
					tbar : {
						xtype : 'container',layout : 'anchor',
						height : 27,style:'font-size:14px',
						defaults : {
							height : 27,anchor : '100%'
						},
						items : [
							new Ext.Toolbar({
								defaults:{
								  scope: this
								},
								items : [
									{
										text: '反选',iconCls : 'icon-reverse',
										handler: function(){
											this.onReverseSelect();
										}
									},/*'-',{
										text : '添加章节评分',iconCls : 'icon-add',
										handler : function() {
											this.addLrating();
										}
									},'-',{
										text : '修改章节评分',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
										handler : function() {
											this.updateLrating();
										}
									},*/'-',{
										text : '删除章节评分', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
										handler : function() {
											this.deleteLrating();
										}
									},'-']}
						)]
					},
					bbar: new Ext.PagingToolbar({
						pageSize: Mt.Chapter.Config.PageSize,
						store: Mt.Chapter.Store.lratingStore,scope:this,autoShow:true,displayInfo: true,
						displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',emptyMsg: "无显示数据",
						items: [
							{xtype:'label', text: '每页显示'},
							{xtype:'numberfield', value:Mt.Chapter.Config.PageSize,minValue:1,width:35,style:'text-align:center',allowBlank: false,
								listeners:
								{
									change:function(Field, newValue, oldValue){
										var num = parseInt(newValue);
										if (isNaN(num) || !num || num<1)
										{
											num = Mt.Chapter.Config.PageSize;
											Field.setValue(num);
										}
										this.ownerCt.pageSize= num;
										Mt.Chapter.Config.PageSize = num;
										this.ownerCt.ownerCt.doSelectLrating();
									},
									specialKey :function(field,e){
										if (e.getKey() == Ext.EventObject.ENTER){
											var num = parseInt(field.getValue());
											if (isNaN(num) || !num || num<1)num = Mt.Chapter.Config.PageSize;
											this.ownerCt.pageSize= num;
											Mt.Chapter.Config.PageSize = num;
											this.ownerCt.ownerCt.doSelectLrating();
										}
									}
								}
							},{xtype:'label', text: '个'}
						]
					})
				}, config);
				/**
				 * 章节评分数据模型获取数据Direct调用
				 */
				Mt.Chapter.Store.lratingStore.proxy=new Ext.data.DirectProxy({
					api: {read:ExtServiceLrating.queryPageLrating}
				});
				Mt.Chapter.View.LratingView.Grid.superclass.constructor.call(this, config);
			},
			/**
			 * 行选择器
			 */
			sm : new Ext.grid.CheckboxSelectionModel({
				listeners : {
					selectionchange:function(sm) {
						// 判断删除和更新按钮是否可以激活
						this.grid.btnRemove.setDisabled(sm.getCount() < 1);
						// this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
					}
				}
			}),
			/**
			 * 查询符合条件的章节评分
			 */
			doSelectLrating : function() {
				if (Mt.Chapter.View.Running.chapterGrid&&Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected()){
					var chapter_id = Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.chapter_id;
					var condition = {'chapter_id':chapter_id,'start':0,'limit':Mt.Chapter.Config.PageSize};
					this.filter     ={'chapter_id':chapter_id};
					ExtServiceLrating.queryPageLrating(condition,function(provider, response) {
						if (response.result){
							if (response.result.data) {
								var result       = new Array();
								result['data']     =response.result.data;
								result['totalCount'] =response.result.totalCount;
								Mt.Chapter.Store.lratingStore.loadData(result);
							} else {
								Mt.Chapter.Store.lratingStore.removeAll();
								Ext.Msg.alert('提示', '无符合条件的章节评分！');
							}

							if (Mt.Chapter.Store.lratingStore.getTotalCount()>Mt.Chapter.Config.PageSize){
								 Mt.Chapter.View.Running.lratingGrid.bottomToolbar.show();
							}else{
								 Mt.Chapter.View.Running.lratingGrid.bottomToolbar.hide();
							}
							Mt.Chapter.View.Running.chapterGrid.ownerCt.doLayout();
						}
					});
				}
			},
			/**
			 * 反选
			 */
			onReverseSelect:function() {
				for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
					if (this.sm.isSelected(i)) {
						this.sm.deselectRow(i);
					}else {
						this.sm.selectRow(i, true);
					}
				}
			},
			/**
			 * 新建章节评分
			 */
			addLrating : function(){
				if (Mt.Chapter.View.LratingView.edit_window==null){
					Mt.Chapter.View.LratingView.edit_window=new Mt.Chapter.View.LratingView.EditWindow();
				}
				Mt.Chapter.View.LratingView.edit_window.resetBtn.setVisible(false);
				Mt.Chapter.View.LratingView.edit_window.saveBtn.setText('保 存');
				Mt.Chapter.View.LratingView.edit_window.setTitle('添加章节评分');
				Mt.Chapter.View.LratingView.edit_window.savetype=0;
				Mt.Chapter.View.LratingView.edit_window.lrating_id.setValue("");
				var company_id = Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.chapter_id;
				Mt.Chapter.View.LratingView.edit_window.chapter_id.setValue(company_id);

				Mt.Chapter.View.LratingView.edit_window.show();
				Mt.Chapter.View.LratingView.edit_window.maximize();
			},
			/**
			 * 编辑章节评分时先获得选中的章节评分信息
			 */
			updateLrating : function() {
				if (Mt.Chapter.View.LratingView.edit_window==null){
					Mt.Chapter.View.LratingView.edit_window=new Mt.Chapter.View.LratingView.EditWindow();
				}
				Mt.Chapter.View.LratingView.edit_window.saveBtn.setText('修 改');
				Mt.Chapter.View.LratingView.edit_window.resetBtn.setVisible(true);
				Mt.Chapter.View.LratingView.edit_window.setTitle('修改章节评分');
				Mt.Chapter.View.LratingView.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
				Mt.Chapter.View.LratingView.edit_window.savetype=1;

				Mt.Chapter.View.LratingView.edit_window.show();
				Mt.Chapter.View.LratingView.edit_window.maximize();
			},
			/**
			 * 删除章节评分
			 */
			deleteLrating : function() {
				Ext.Msg.confirm('提示', '确实要删除所选的章节评分吗?', this.confirmDeleteLrating,this);
			},
			/**
			 * 确认删除章节评分
			 */
			confirmDeleteLrating : function(btn) {
				if (btn == 'yes') {
					var del_lrating_ids ="";
					var selectedRows  = this.getSelectionModel().getSelections();
					for ( var flag = 0; flag < selectedRows.length; flag++) {
						del_lrating_ids=del_lrating_ids+selectedRows[flag].data.lrating_id+",";
					}
					ExtServiceLrating.deleteByIds(del_lrating_ids);
					this.doSelectLrating();
					Ext.Msg.alert("提示", "删除成功！");
				}
			}
		})
	},
	/**
	 * 视图：练习题列表
	 */
	PracticeView:{
		/**
		 *  当前创建的练习题编辑窗口
		 */
		edit_window:null,
		/**
		 * 编辑窗口：新建或者修改练习题
		 */
		EditWindow:Ext.extend(Ext.Window,{
			constructor : function(config) {
				config = Ext.apply({
					/**
					 * 自定义类型:保存类型
					 * 0:保存窗口,1:修改窗口
					 */
					savetype:0,closeAction : "hide",constrainHeader:true,maximizable: true,collapsible: true,
					width : 450,height : 550,minWidth : 400,minHeight : 450,
					layout : 'fit',plain : true,buttonAlign : 'center',
					defaults : {autoScroll : true},
					listeners:{
						beforehide:function(){
							this.editForm.form.getEl().dom.reset();
						},
            afterrender:function(){
              switch (Mt.Chapter.Config.OnlineEditor)
              {
                  case 1:
                      ckeditor_replace_practice_title();
                      // ckeditor_replace_options_json();
                      // ckeditor_replace_answer();
                      break
                  case 2:
                      Mt.Chapter.View.PracticeView.EditWindow.KindEditor_practice_title = KindEditor.create('textarea[name="practice_title"]',{width:'98%',minHeith:'350px', filterMode:true});
                      // Mt.Chapter.View.PracticeView.EditWindow.KindEditor_options_json = KindEditor.create('textarea[name="options_json"]',{width:'98%',minHeith:'350px', filterMode:true});
                      // Mt.Chapter.View.PracticeView.EditWindow.KindEditor_answer = KindEditor.create('textarea[name="answer"]',{width:'98%',minHeith:'350px', filterMode:true});
                      break
                  case 3:
                      pageInit_practice_title();
                      // pageInit_options_json();
                      // pageInit_answer();
                      break
                  default:
                      this.editForm.practice_title.setWidth("98%");
                      pageInit_ue_practice_title();
                      // this.editForm.options_json.setWidth("98%");
                      // pageInit_ue_options_json();
                      // this.editForm.answer.setWidth("98%");
                      // pageInit_ue_answer();
              }
            }
					},
					items : [
						new Ext.form.FormPanel({
							ref:'editForm',layout:'form',
							labelWidth : 100,labelAlign : "center",
							bodyStyle : 'padding:5px 5px 0',align : "center",
							api : {},
							defaults : {
								xtype : 'textfield',anchor:'98%'
							},
							items : [
                {xtype: 'hidden',name : 'practice_id',ref:'../practice_id'},
                {xtype: 'hidden',name : 'lesson_id',ref:'../lesson_id'},
                /*{
                   fieldLabel : '课程',xtype: 'combo',name : 'lesson_name',ref : '../lesson_name',
                   store:Mt.Chapter.Store.lessonStoreForCombo,emptyText: '请选择课程',itemSelector: 'div.search-item',
                   loadingText: '查询中...',width: 570, pageSize:Mt.Chapter.Config.PageSize,
                   displayField:'lesson_name',grid:this,
                   mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                     '<tpl for="."><div class="search-item">',
                       '<h3>{lesson_name}</h3>',
                     '</div></tpl>'
                   ),
                   listeners:{
                     'beforequery': function(event){delete event.combo.lastQuery;}
                   },
                   onSelect:function(record,index){
                     if(this.fireEvent('beforeselect', this, record, index) !== false){
                      this.grid.lesson_id.setValue(record.data.lesson_id);
                      this.grid.lesson_name.setValue(record.data.lesson_name);
                      this.collapse();
                     }
                   }
                },*/
                {xtype: 'hidden',name : 'chapter_id',ref:'../chapter_id'},
                {xtype: 'hidden',name : 'options_json',ref:'../options_json'},
                {fieldLabel : '题干',name : 'practice_title',xtype : 'textarea',id:'practice_title',ref:'practice_title'}, 
                {fieldLabel : '分值',name : 'point',xtype : 'numberfield'},
                {fieldLabel : '排序',name : 'sort_order',xtype : 'numberfield'},
                {fieldLabel : '是否显示',hiddenName : 'isShow'
                     ,xtype:'combo',ref:'../isShow',mode : 'local',triggerAction : 'all',
                     lazyRender : true,editable: false,allowBlank : false,valueNotFoundText:'否',
                     store : new Ext.data.SimpleStore({
                         fields : ['value', 'text'],
                         data : [['0', '否'], ['1', '是']]
                     }),emptyText: '请选择是否显示',
                     valueField : 'value',displayField : 'text'
                },
                Mt.Chapter.View.Running.optionGrid
							]
						})
					],
					buttons : [{
						text: "",ref : "../saveBtn",scope:this,
						handler : function() {
              switch (Mt.Chapter.Config.OnlineEditor)
              {
                  case 1:
                      if (CKEDITOR.instances.practice_title) this.editForm.practice_title.setValue(CKEDITOR.instances.practice_title.getData());
                      // if (CKEDITOR.instances.options_json) this.editForm.options_json.setValue(CKEDITOR.instances.options_json.getData());
                      // if (CKEDITOR.instances.answer) this.editForm.answer.setValue(CKEDITOR.instances.answer.getData());
                      break
                  case 2:
                      if (Mt.Chapter.View.PracticeView.EditWindow.KindEditor_practice_title)this.editForm.practice_title.setValue(Mt.Chapter.View.PracticeView.EditWindow.KindEditor_practice_title.html());
                      // if (Mt.Chapter.View.PracticeView.EditWindow.KindEditor_options_json)this.editForm.options_json.setValue(Mt.Chapter.View.PracticeView.EditWindow.KindEditor_options_json.html());
                      // if (Mt.Chapter.View.PracticeView.EditWindow.KindEditor_answer)this.editForm.answer.setValue(Mt.Chapter.View.PracticeView.EditWindow.KindEditor_answer.html());
                      break
                  case 3:
                      if (xhEditor_practice_title)this.editForm.practice_title.setValue(xhEditor_practice_title.getSource());
                      // if (xhEditor_options_json)this.editForm.options_json.setValue(xhEditor_options_json.getSource());
                      // if (xhEditor_answer)this.editForm.answer.setValue(xhEditor_answer.getSource());
                      break
                  default:
                      if (ue_practice_title)this.editForm.practice_title.setValue(ue_practice_title.getContent());
                      // if (ue_options_json)this.editForm.options_json.setValue(ue_options_json.getContent());
                      // if (ue_answer)this.editForm.answer.setValue(ue_answer.getContent());
              }
							if (!this.editForm.getForm().isValid()) {
								return;
							}
              var option_store = Mt.Chapter.View.Running.optionGrid.store;
              if (option_store.getCount() < 2) {
                Ext.Msg.alert("提示", "请添加至少2个选项");
                return;
              };

              var optsions_json=new Array();
              var has_current_option=false;

              option_store.each(function(record) {
                  optsions_json.push(record.data);
                  if (!has_current_option) {
                    has_current_option = record.data.current;
                  };
              });

              if (!has_current_option) {
                Ext.Msg.alert("提示", "请添加至少1个正确选项");
                return;
              };
              this.editForm.getForm().findField('options_json').setValue(Ext.encode(optsions_json));

							editWindow=this;
							if (this.savetype==0){
								this.editForm.api.submit=ExtServicePractice.save;
								this.editForm.getForm().submit({
									success : function(form, action) {
										Ext.Msg.alert("提示", "保存成功！");
										Mt.Chapter.View.Running.practiceGrid.doSelectPractice();
										form.reset();
										editWindow.hide();
									},
									failure : function(form, response) {
										Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
									}
								});
							}else{
								this.editForm.api.submit=ExtServicePractice.update;
								this.editForm.getForm().submit({
									success : function(form, action) {
										Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
											Mt.Chapter.View.Running.practiceGrid.bottomToolbar.doRefresh();
										}});
										form.reset();
										editWindow.hide();
									},
									failure : function(form, response) {
										Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
									}
								});
							}
						}
					}, {
						text : "取 消",scope:this,
						handler : function() {
							this.hide();
						}
					}, {
						text : "重 置",ref:'../resetBtn',scope:this,
						handler : function() {
							this.editForm.form.loadRecord(Mt.Chapter.View.Running.practiceGrid.getSelectionModel().getSelected());
              switch (Mt.Chapter.Config.OnlineEditor)
              {
                  case 1:
                      if (CKEDITOR.instances.practice_title) CKEDITOR.instances.practice_title.setData(Mt.Chapter.View.Running.practiceGrid.getSelectionModel().getSelected().data.practice_title);
                      // if (CKEDITOR.instances.options_json) CKEDITOR.instances.options_json.setData(Mt.Chapter.View.Running.practiceGrid.getSelectionModel().getSelected().data.options_json);
                      // if (CKEDITOR.instances.answer) CKEDITOR.instances.answer.setData(Mt.Chapter.View.Running.practiceGrid.getSelectionModel().getSelected().data.answer);
                      break
                  case 2:
                      if (Mt.Chapter.View.PracticeView.EditWindow.KindEditor_practice_title) Mt.Chapter.View.PracticeView.EditWindow.KindEditor_practice_title.html(Mt.Chapter.View.Running.practiceGrid.getSelectionModel().getSelected().data.practice_title);
                      // if (Mt.Chapter.View.PracticeView.EditWindow.KindEditor_options_json) Mt.Chapter.View.PracticeView.EditWindow.KindEditor_options_json.html(Mt.Chapter.View.Running.practiceGrid.getSelectionModel().getSelected().data.options_json);
                      // if (Mt.Chapter.View.PracticeView.EditWindow.KindEditor_answer) Mt.Chapter.View.PracticeView.EditWindow.KindEditor_answer.html(Mt.Chapter.View.Running.practiceGrid.getSelectionModel().getSelected().data.answer);
                      break
                  case 3:
                      if (xhEditor_practice_title) xhEditor_practice_title.setSource(Mt.Chapter.View.Running.practiceGrid.getSelectionModel().getSelected().data.practice_title);
                      // if (xhEditor_options_json) xhEditor_options_json.setSource(Mt.Chapter.View.Running.practiceGrid.getSelectionModel().getSelected().data.options_json);
                      // if (xhEditor_answer) xhEditor_answer.setSource(Mt.Chapter.View.Running.practiceGrid.getSelectionModel().getSelected().data.answer);
                      break
                  default:
                      if (ue_practice_title) ue_practice_title.setContent(Mt.Chapter.View.Running.practiceGrid.getSelectionModel().getSelected().data.practice_title);
                      // if (ue_options_json) ue_options_json.setContent(Mt.Chapter.View.Running.practiceGrid.getSelectionModel().getSelected().data.options_json);
                      // if (ue_answer) ue_answer.setContent(Mt.Chapter.View.Running.practiceGrid.getSelectionModel().getSelected().data.answer);
              }

						}
					}]
				}, config);
				Mt.Chapter.View.PracticeView.EditWindow.superclass.constructor.call(this, config);
			}
		}),
		/**
		 * 查询条件
		 */
		filter:null,
		/**
		 * 视图：练习题列表
		 */
		Grid:Ext.extend(Ext.grid.GridPanel, {
			constructor : function(config) {
				config = Ext.apply({
					store : Mt.Chapter.Store.practiceStore,sm : this.sm,
					frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
					loadMask : true,stripeRows : true,headerAsText : false,
					defaults : {autoScroll : true},
					cm : new Ext.grid.ColumnModel({
						defaults:{
							width:120,sortable : true
						},
						columns : [
              this.sm,
              {header : '标识',dataIndex : 'practice_id',hidden:true},
              {header : '课程',dataIndex : 'lesson_name'},
              {header : '题干',dataIndex : 'practice_title'},
              // {header : '选项',dataIndex : 'options_json'},
              // {header : '答案',dataIndex : 'answer'},
              {header : '分值',dataIndex : 'point'},
              {header : '排序',dataIndex : 'sort_order'}
						]
					}),
					tbar : {
						xtype : 'container',layout : 'anchor',
						height : 27,style:'font-size:14px',
						defaults : {
							height : 27,anchor : '100%'
						},
						items : [
							new Ext.Toolbar({
								defaults:{
								  scope: this
								},
								items : [
									{
										text: '反选',iconCls : 'icon-reverse',
										handler: function(){
											this.onReverseSelect();
										}
									},'-',{
										text : '添加练习题',iconCls : 'icon-add',
										handler : function() {
											this.addPractice();
										}
									},'-',{
										text : '修改练习题',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
										handler : function() {
											this.updatePractice();
										}
									},'-',{
										text : '删除练习题', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
										handler : function() {
											this.deletePractice();
										}
									},'-']}
						)]
					},
					bbar: new Ext.PagingToolbar({
						pageSize: Mt.Chapter.Config.PageSize,
						store: Mt.Chapter.Store.practiceStore,scope:this,autoShow:true,displayInfo: true,
						displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',emptyMsg: "无显示数据",
						items: [
							{xtype:'label', text: '每页显示'},
							{xtype:'numberfield', value:Mt.Chapter.Config.PageSize,minValue:1,width:35,style:'text-align:center',allowBlank: false,
								listeners:
								{
									change:function(Field, newValue, oldValue){
										var num = parseInt(newValue);
										if (isNaN(num) || !num || num<1)
										{
											num = Mt.Chapter.Config.PageSize;
											Field.setValue(num);
										}
										this.ownerCt.pageSize= num;
										Mt.Chapter.Config.PageSize = num;
										this.ownerCt.ownerCt.doSelectPractice();
									},
									specialKey :function(field,e){
										if (e.getKey() == Ext.EventObject.ENTER){
											var num = parseInt(field.getValue());
											if (isNaN(num) || !num || num<1)num = Mt.Chapter.Config.PageSize;
											this.ownerCt.pageSize= num;
											Mt.Chapter.Config.PageSize = num;
											this.ownerCt.ownerCt.doSelectPractice();
										}
									}
								}
							},{xtype:'label', text: '个'}
						]
					})
				}, config);
				/**
				 * 练习题数据模型获取数据Direct调用
				 */
				Mt.Chapter.Store.practiceStore.proxy=new Ext.data.DirectProxy({
					api: {read:ExtServicePractice.queryPagePractice}
				});
				Mt.Chapter.View.PracticeView.Grid.superclass.constructor.call(this, config);
			},
			/**
			 * 行选择器
			 */
			sm : new Ext.grid.CheckboxSelectionModel({
				listeners : {
					selectionchange:function(sm) {
						// 判断删除和更新按钮是否可以激活
						this.grid.btnRemove.setDisabled(sm.getCount() < 1);
						this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
					}
				}
			}),
			/**
			 * 查询符合条件的练习题
			 */
			doSelectPractice : function() {
				if (Mt.Chapter.View.Running.chapterGrid&&Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected()){
					var chapter_id = Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.chapter_id;
					var condition = {'chapter_id':chapter_id,'start':0,'limit':Mt.Chapter.Config.PageSize};
					this.filter     ={'chapter_id':chapter_id};
					ExtServicePractice.queryPagePractice(condition,function(provider, response) {
						if (response.result){
							if (response.result.data) {
								var result       = new Array();
								result['data']     =response.result.data;
								result['totalCount'] =response.result.totalCount;
								Mt.Chapter.Store.practiceStore.loadData(result);
							} else {
								Mt.Chapter.Store.practiceStore.removeAll();
								Ext.Msg.alert('提示', '无符合条件的练习题！');
							}

							if (Mt.Chapter.Store.practiceStore.getTotalCount()>Mt.Chapter.Config.PageSize){
								 Mt.Chapter.View.Running.practiceGrid.bottomToolbar.show();
							}else{
								 Mt.Chapter.View.Running.practiceGrid.bottomToolbar.hide();
							}
							Mt.Chapter.View.Running.chapterGrid.ownerCt.doLayout();
						}
					});
				}
			},
			/**
			 * 反选
			 */
			onReverseSelect:function() {
				for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
					if (this.sm.isSelected(i)) {
						this.sm.deselectRow(i);
					}else {
						this.sm.selectRow(i, true);
					}
				}
			},
			/**
			 * 新建练习题
			 */
			addPractice : function(){
        if (Mt.Chapter.View.Running.optionGrid==null){
          Mt.Chapter.View.Running.optionGrid = new Mt.Chapter.View.OptionView.Grid();
        }
        Mt.Chapter.View.Running.optionGrid.store.loadData([]);

				if (Mt.Chapter.View.PracticeView.edit_window==null){
					Mt.Chapter.View.PracticeView.edit_window=new Mt.Chapter.View.PracticeView.EditWindow();
				}
				Mt.Chapter.View.PracticeView.edit_window.resetBtn.setVisible(false);
				Mt.Chapter.View.PracticeView.edit_window.saveBtn.setText('保 存');
				Mt.Chapter.View.PracticeView.edit_window.setTitle('添加练习题');
				Mt.Chapter.View.PracticeView.edit_window.savetype=0;
				Mt.Chapter.View.PracticeView.edit_window.practice_id.setValue("");
				var chapter = Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data;
				Mt.Chapter.View.PracticeView.edit_window.chapter_id.setValue(chapter.chapter_id);

        Mt.Chapter.View.PracticeView.edit_window.lesson_id.setValue(chapter.lesson_id);
        switch (Mt.Chapter.Config.OnlineEditor)
        {
            case 1:
                if (CKEDITOR.instances.practice_title) CKEDITOR.instances.practice_title.setData("");
                // if (CKEDITOR.instances.options_json) CKEDITOR.instances.options_json.setData("");
                // if (CKEDITOR.instances.answer) CKEDITOR.instances.answer.setData("");
                break
            case 2:
                if (Mt.Chapter.View.PracticeView.EditWindow.KindEditor_practice_title) Mt.Chapter.View.PracticeView.EditWindow.KindEditor_practice_title.html("");
                // if (Mt.Chapter.View.PracticeView.EditWindow.KindEditor_options_json) Mt.Chapter.View.PracticeView.EditWindow.KindEditor_options_json.html("");
                // if (Mt.Chapter.View.PracticeView.EditWindow.KindEditor_answer) Mt.Chapter.View.PracticeView.EditWindow.KindEditor_answer.html("");
                break
            case 3:
                break
            default:
                if (ue_practice_title)ue_practice_title.setContent("");
                // if (ue_options_json)ue_options_json.setContent("");
                // if (ue_answer)ue_answer.setContent("");
        }

				Mt.Chapter.View.PracticeView.edit_window.show();
				Mt.Chapter.View.PracticeView.edit_window.maximize();
			},
			/**
			 * 编辑练习题时先获得选中的练习题信息
			 */
			updatePractice : function() {
        if (Mt.Chapter.View.Running.optionGrid==null){
          Mt.Chapter.View.Running.optionGrid = new Mt.Chapter.View.OptionView.Grid();
        }
				if (Mt.Chapter.View.PracticeView.edit_window==null){
					Mt.Chapter.View.PracticeView.edit_window=new Mt.Chapter.View.PracticeView.EditWindow();
				}
				Mt.Chapter.View.PracticeView.edit_window.saveBtn.setText('修 改');
				Mt.Chapter.View.PracticeView.edit_window.resetBtn.setVisible(true);
				Mt.Chapter.View.PracticeView.edit_window.setTitle('修改练习题');
				Mt.Chapter.View.PracticeView.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
				Mt.Chapter.View.PracticeView.edit_window.savetype=1;
        
        // var chapter = Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data;
        // Mt.Chapter.View.PracticeView.edit_window.chapter_id.setValue(chapter.chapter_id);

        // Mt.Chapter.View.PracticeView.edit_window.lesson_id.setValue(chapter.lesson_id);

        var data = Ext.decode(this.getSelectionModel().getSelected().data.options_json);
        Mt.Chapter.Store.optionStore.loadData(data);
        switch (Mt.Chapter.Config.OnlineEditor)
        {
            case 1:
                if (CKEDITOR.instances.practice_title) CKEDITOR.instances.practice_title.setData(this.getSelectionModel().getSelected().data.practice_title);
                // if (CKEDITOR.instances.options_json) CKEDITOR.instances.options_json.setData(this.getSelectionModel().getSelected().data.options_json);
                // if (CKEDITOR.instances.answer) CKEDITOR.instances.answer.setData(this.getSelectionModel().getSelected().data.answer);
                break
            case 2:
                if (Mt.Chapter.View.PracticeView.EditWindow.KindEditor_practice_title) Mt.Chapter.View.PracticeView.EditWindow.KindEditor_practice_title.html(this.getSelectionModel().getSelected().data.practice_title);
                // if (Mt.Chapter.View.PracticeView.EditWindow.KindEditor_options_json) Mt.Chapter.View.PracticeView.EditWindow.KindEditor_options_json.html(this.getSelectionModel().getSelected().data.options_json);
                // if (Mt.Chapter.View.PracticeView.EditWindow.KindEditor_answer) Mt.Chapter.View.PracticeView.EditWindow.KindEditor_answer.html(this.getSelectionModel().getSelected().data.answer);
                break
            case 3:
                if (xhEditor_practice_title)xhEditor_practice_title.setSource(this.getSelectionModel().getSelected().data.practice_title);
                // if (xhEditor_options_json)xhEditor_options_json.setSource(this.getSelectionModel().getSelected().data.options_json);
                // if (xhEditor_answer)xhEditor_answer.setSource(this.getSelectionModel().getSelected().data.answer);
                break
            default:
                if (ue_practice_title)ue_practice_title.setContent(this.getSelectionModel().getSelected().data.practice_title);
                // if (ue_options_json)ue_options_json.setContent(this.getSelectionModel().getSelected().data.options_json);
                // if (ue_answer)ue_answer.setContent(this.getSelectionModel().getSelected().data.answer);
        }
				Mt.Chapter.View.PracticeView.edit_window.show();
				Mt.Chapter.View.PracticeView.edit_window.maximize();
			},
			/**
			 * 删除练习题
			 */
			deletePractice : function() {
				Ext.Msg.confirm('提示', '确实要删除所选的练习题吗?', this.confirmDeletePractice,this);
			},
			/**
			 * 确认删除练习题
			 */
			confirmDeletePractice : function(btn) {
				if (btn == 'yes') {
					var del_practice_ids ="";
					var selectedRows  = this.getSelectionModel().getSelections();
					for ( var flag = 0; flag < selectedRows.length; flag++) {
						del_practice_ids=del_practice_ids+selectedRows[flag].data.practice_id+",";
					}
					ExtServicePractice.deleteByIds(del_practice_ids);
					this.doSelectPractice();
					Ext.Msg.alert("提示", "删除成功！");
				}
			}
		})
	},
  OptionView:{
      /**
       *  当前创建的选项编辑窗口
       */
      edit_window:null,
      /**
       * 编辑窗口：新建或者修改选项
       */
      EditWindow:Ext.extend(Ext.Window,{
        constructor : function(config) {
          config = Ext.apply({
            /**
             * 自定义类型:保存类型
             * 0:保存窗口,1:修改窗口
             */
            savetype:0,closeAction : "hide",constrainHeader:true,maximizable: true,collapsible: true,modal: true,
            width : 450,height : 200,minWidth : 400,minHeight : 200,
            layout : 'fit',plain : true,buttonAlign : 'center',
            defaults : {autoScroll : true},
            listeners:{
              beforehide:function(){
                this.editForm.form.getEl().dom.reset();
              }
            },
            items : [
              new Ext.form.FormPanel({
                ref:'editForm',layout:'form',
                labelWidth : 100,labelAlign : "center",
                bodyStyle : 'padding:5px 5px 0',align : "center",
                api : {},
                defaults : {
                  xtype : 'textfield',anchor:'98%'
                },
                items : [
                  {xtype: 'hidden',name : 'oid',ref:'../oid'},
                  {fieldLabel : '选项',name : 'title',ref:'../otitle',xtype : 'textarea',allowBlank : false }
                ]
              })
            ],
            buttons : [{
              text: "",ref : "../saveBtn",scope:this,
              handler : function() {

                if (!this.editForm.getForm().isValid()) {
                  return;
                }
                editWindow=this;

                var option_store = Mt.Chapter.Store.optionStore;
                var OptionRecord = Ext.data.Record.create([
                       {name: 'oid', type: 'string'},
                       {name: 'title', type: 'string'},
                       {name: 'current', type: 'int'},
                   ]);

                if (this.savetype==0){//保存

                   var record = new OptionRecord({
                       oid: '',
                       title: editWindow.otitle.getValue(),
                       current: 0
                   });

                   record.set('oid',record.id.replace('ext-record-',''));
                   record.commit();
                   option_store.add(record);

                }else{//修改
                 var oid = Mt.Chapter.View.Running.optionGrid.getSelectionModel().getSelected().id;
            
                 var index = option_store.find('oid',oid);
                 var record = option_store.getById(oid);

                 record.set('title',editWindow.otitle.getValue());
                 record.set('current',editWindow.current.getValue());
                 record.commit();
                }
                editWindow.editForm.getForm().reset()
                editWindow.hide(); 
              }
            }, {
              text : "取 消",scope:this,
              handler : function() {
                this.hide();
              }
            }, {
              text : "重 置",ref:'../resetBtn',scope:this,
              handler : function() {
                this.editForm.form.loadRecord(Mt.Chapter.View.Running.optionGrid.getSelectionModel().getSelected());

              }
            }]
          }, config);
          Mt.Chapter.View.OptionView.EditWindow.superclass.constructor.call(this, config);
        }
      }),
      /**
       * 查询条件
       */
      filter:null,
      /**
       * 视图：选项列表
       */
      Grid:Ext.extend(Ext.grid.GridPanel, {
        constructor : function(config) {
          config = Ext.apply({
            store : Mt.Chapter.Store.optionStore,height:210,
            sm : this.sm,
            frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
            loadMask : true,stripeRows : true,headerAsText : false,
            defaults : {autoScroll : true},
            cm : new Ext.grid.ColumnModel({
              defaults:{
                width:120,sortable : true
              },
              columns : [
                this.sm,
                {header : '标识',dataIndex : 'oid',hidden:true},
                {header : '选项',dataIndex : 'title',width:500},
                {header : '正确答案',dataIndex : 'current',renderer:function(value){
                    return value == 1 ? "是" : "否"
                  }
                },
              ]
            }),
            tbar : {
              xtype : 'container',layout : 'anchor',
              height : 27,style:'font-size:14px',
              defaults : {
                height : 27,anchor : '100%'
              },
              items : [
                new Ext.Toolbar({
                  defaults:{
                    scope: this
                  },
                  items : [
                    {
                      text: '反选',iconCls : 'icon-reverse',
                      handler: function(){
                        this.onReverseSelect();
                      }
                    },'-',{
                      text : '添加选项',iconCls : 'icon-add',
                      handler : function() {
                        this.addOption();
                      }
                    },'-',{
                      text : '修改选项',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
                      handler : function() {
                        this.updateOption();
                      }
                    },'-',{
                      text : '删除选项', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
                      handler : function() {
                        this.deleteOption();
                      }
                    },'-',
                    {
                      text : '切换正确答案', ref: '../../btnAnswer',iconCls : 'icon-edit',disabled : true,
                      handler : function() {
                         this.changeAnswer();
                      }
                    },'-']}
              )]
            } 
          }, config);
          /**
           * 选项数据模型获取数据Direct调用
           */
          Mt.Chapter.View.OptionView.Grid.superclass.constructor.call(this, config);
        },
        /**
         * 行选择器
         */
        sm : new Ext.grid.CheckboxSelectionModel({
          listeners : {
            selectionchange:function(sm) {
              // 判断删除和更新按钮是否可以激活
              this.grid.btnRemove.setDisabled(sm.getCount() < 1);
              this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
              this.grid.btnAnswer.setDisabled(sm.getCount() != 1);
            }
          }
        }),
        /**
         * 查询符合条件的选项
         */
        doSelectOption : function() {
          
        },
        /**
         * 反选
         */
        onReverseSelect:function() {
          for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
            if (this.sm.isSelected(i)) {
              this.sm.deselectRow(i);
            }else {
              this.sm.selectRow(i, true);
            }
          }
        },
        /**
         * 新建选项
         */
        addOption : function(){
          if (Mt.Chapter.View.OptionView.edit_window==null){
            Mt.Chapter.View.OptionView.edit_window=new Mt.Chapter.View.OptionView.EditWindow();
          }
          Mt.Chapter.View.OptionView.edit_window.resetBtn.setVisible(false);
          Mt.Chapter.View.OptionView.edit_window.saveBtn.setText('保 存');
          Mt.Chapter.View.OptionView.edit_window.setTitle('添加选项');
          Mt.Chapter.View.OptionView.edit_window.savetype=0;
          Mt.Chapter.View.OptionView.edit_window.oid.setValue("");
          Mt.Chapter.View.OptionView.edit_window.show(); 
        },
        /**
         * 编辑选项时先获得选中的选项信息
         */
        updateOption : function() {
          if (Mt.Chapter.View.OptionView.edit_window==null){
            Mt.Chapter.View.OptionView.edit_window=new Mt.Chapter.View.OptionView.EditWindow();
          }
          Mt.Chapter.View.OptionView.edit_window.saveBtn.setText('修 改');
          Mt.Chapter.View.OptionView.edit_window.resetBtn.setVisible(true);
          Mt.Chapter.View.OptionView.edit_window.setTitle('修改选项');
          Mt.Chapter.View.OptionView.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
          Mt.Chapter.View.OptionView.edit_window.savetype=1;

          Mt.Chapter.View.OptionView.edit_window.show(); 
        },
        /**
         * 删除选项
         */
        deleteOption : function() {
          Ext.Msg.confirm('提示', '确实要删除所选的选项吗?', this.confirmDeleteOption,this);
        },

        changeAnswer : function() {
          var option_store = Mt.Chapter.Store.optionStore;
          var option = this.getSelectionModel().getSelected().data;

          var oid = Mt.Chapter.View.Running.optionGrid.getSelectionModel().getSelected().id;
          var record = option_store.getById(oid);
          
          if (option.current == 1) {
            record.set('current',0);
          }else{
            record.set('current',1);
          }
          record.commit();
        },

        /**
         * 确认删除选项
         */
        confirmDeleteOption : function(btn) {
          if (btn == 'yes') {

            var oid = Mt.Chapter.View.Running.optionGrid.getSelectionModel().getSelected().data.oid;
            var option_store = Mt.Chapter.Store.optionStore;

            var del_oid ="";
            var selectedRows    = this.getSelectionModel().getSelections();
            for ( var flag = 0; flag < selectedRows.length; flag++) {
              del_oid = selectedRows[flag].data.oid;
              option_store.removeAt(option_store.find('oid',del_oid));
            }
            this.doSelectOption();
            Ext.Msg.alert("提示", "删除成功！");
          }
        }
      })
    },
	/**
	 * 窗口：批量上传章节
	 */
	UploadWindow:Ext.extend(Ext.Window,{
		constructor : function(config) {
			config = Ext.apply({
				title : '批量上传章节数据',width : 400,height : 110,minWidth : 300,minHeight : 100,
				layout : 'fit',plain : true,bodyStyle : 'padding:5px;',buttonAlign : 'center',closeAction : "hide",
				items : [
					new Ext.form.FormPanel({
						ref:'uploadForm',fileUpload: true,
						width: 500,labelWidth: 50,autoHeight: true,baseCls: 'x-plain',
						frame:true,bodyStyle: 'padding: 10px 10px 10px 10px;',
						defaults: {
							anchor: '95%',allowBlank: false,msgTarget: 'side'
						},
						items : [{
							xtype : 'fileuploadfield',
							fieldLabel : '文 件',name : 'upload_file',ref:'upload_file',
							emptyText: '请上传章节Excel文件',buttonText: '',
							accept:'application/vnd.ms-excel',
							buttonCfg: {iconCls: 'upload-icon'}
						}]
					})
				],
				buttons : [{
						text : '上 传',
						scope:this,
						handler : function() {
							uploadWindow       =this;
							validationExpression   =/([\u4E00-\u9FA5]|\w)+(.xlsx|.XLSX|.xls|.XLS)$/;/**允许中文名*/
							var isValidExcelFormat = new RegExp(validationExpression);
							var result       = isValidExcelFormat.test(this.uploadForm.upload_file.getValue());
							if (!result){
								Ext.Msg.alert('提示', '请上传Excel文件，后缀名为xls或者xlsx！');
								return;
							}
							if (this.uploadForm.getForm().isValid()) {
								Ext.Msg.show({
									title : '请等待',msg : '文件正在上传中，请稍后...',
									animEl : 'loading',icon : Ext.Msg.WARNING,
									closable : true,progress : true,progressText : '',width : 300
								});
								this.uploadForm.getForm().submit({
									url : 'index.php?go=admin.upload.uploadChapter',
									success : function(form, response) {
										Ext.Msg.alert('成功', '上传成功');
										uploadWindow.hide();
										uploadWindow.uploadForm.upload_file.setValue('');
										Mt.Chapter.View.Running.chapterGrid.doSelectChapter();
									},
									failure : function(form, response) {
										Ext.Msg.alert('错误', response.result.data);
									}
								});
							}
						}
					},{
						text : '取 消',
						scope:this,
						handler : function() {
							this.uploadForm.upload_file.setValue('');
							this.hide();
						}
					}]
				}, config);
			Mt.Chapter.View.UploadWindow.superclass.constructor.call(this, config);
		}
	}),
  PracticeUploadWindow:Ext.extend(Ext.Window,{
    constructor : function(config) {
      config = Ext.apply({
        title : '批量上传章节练习数据',width : 400,height : 150,minWidth : 300,minHeight : 100,
        layout : 'fit',plain : true,bodyStyle : 'padding:5px;',buttonAlign : 'center',closeAction : "hide",
        items : [
          new Ext.form.FormPanel({
            ref:'uploadForm',fileUpload: true,
            width: 500,labelWidth: 50,autoHeight: true,baseCls: 'x-plain',
            frame:true,bodyStyle: 'padding: 10px 10px 10px 10px;',
            defaults: {
              anchor: '95%',allowBlank: false,msgTarget: 'side'
            },
            items : [
              {xtype:'label',ref:'../chapter_name'},
              {xtype:'hidden',name:'chapter_id',ref:'../chapter_id'},
              {
                xtype : 'fileuploadfield',
                fieldLabel : '文 件',name : 'upload_file',ref:'upload_file',
                emptyText: '请上传章节练习Excel文件',buttonText: '',
                accept:'application/vnd.ms-excel',
                buttonCfg: {iconCls: 'upload-icon'}
              }
            ]
          })
        ],
        buttons : [{
            text : '上 传',
            scope:this,
            handler : function() {
              uploadWindow       =this;
              validationExpression   =/([\u4E00-\u9FA5]|\w)+(.xlsx|.XLSX|.xls|.XLS)$/;/**允许中文名*/
              var isValidExcelFormat = new RegExp(validationExpression);
              var result       = isValidExcelFormat.test(this.uploadForm.upload_file.getValue());
              if (!result){
                Ext.Msg.alert('提示', '请上传Excel文件，后缀名为xls或者xlsx！');
                return;
              }
              if (this.uploadForm.getForm().isValid()) {
                Ext.Msg.show({
                  title : '请等待',msg : '文件正在上传中，请稍后...',
                  animEl : 'loading',icon : Ext.Msg.WARNING,
                  closable : true,progress : true,progressText : '',width : 300
                });
                this.uploadForm.getForm().submit({
                  url : 'index.php?go=admin.upload.uploadPractice',
                  success : function(form, response) {
                    Ext.Msg.alert('成功', '上传成功');
                    uploadWindow.hide();
                    // uploadWindow.uploadForm.upload_file.setValue('');
                    Mt.Chapter.View.Running.chapterGrid.doSelectChapter();

                  },
                  failure : function(form, response) {
                    Ext.Msg.alert('错误', response.result.data);
                  }
                });
              }
            }
          },{
            text : '取 消',
            scope:this,
            handler : function() {
              this.uploadForm.upload_file.setValue('');
              this.hide();
            }
          }]
        }, config);
      Mt.Chapter.View.PracticeUploadWindow.superclass.constructor.call(this, config);
    }
  }),
	/**
	 * 视图：章节列表
	 */
	Grid:Ext.extend(Ext.grid.GridPanel, {
		constructor : function(config) {
			config = Ext.apply({
				/**
				 * 查询条件
				 */
				filter:null,
				region : 'center',
				store : Mt.Chapter.Store.chapterStore,
				sm : this.sm,
				frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
				loadMask : true,stripeRows : true,headerAsText : false,
				defaults : {
					autoScroll : true
				},
				cm : new Ext.grid.ColumnModel({
					defaults:{
						width:120,sortable : true
					},
					columns : [
						this.sm,
            {header : '标识',dataIndex : 'chapter_id',hidden:true},
            {header : '所属用户',dataIndex : 'admin_name'},
            {header : '课程',dataIndex : 'lesson_name'},
            {header : '章节名称',dataIndex : 'chapter_name'},
            // {header : '内容关键字',dataIndex : 'keywords'},
            {header : '开始时间',dataIndex : 'begin_time',renderer:Ext.util.Format.dateRenderer('Y-m-d')},
            {header : '结束时间',dataIndex : 'end_time',renderer:Ext.util.Format.dateRenderer('Y-m-d')},
            {header : '是否显示',dataIndex : 'isShow',renderer:function(value){if (value == true) {return "是";}else{return "否";}}},
            {header : '是否评论',dataIndex : 'isComment',renderer:function(value){if (value == true) {return "是";}else{return "否";}}},
            {header : '是否打分',dataIndex : 'isScoring',renderer:function(value){if (value == true) {return "是";}else{return "否";}}},
            {header : '是否上传文件',dataIndex : 'isUpload_file',renderer:function(value){if (value == true) {return "是";}else{return "否";}}},
            {header : '是否打开广告',dataIndex : 'isAdvertisement',renderer:function(value){if (value == true) {return "是";}else{return "否";}}},
            {header : '排序',dataIndex : 'sort_order'}
					]
				}),
				tbar : {
					xtype : 'container',layout : 'anchor',height : 27 * 3,style:'font-size:14px',
					defaults : {
						height : 27,anchor : '100%'
					},
					items : [
						new Ext.Toolbar({
							enableOverflow: true,width : 100,
							defaults : {
								xtype : 'textfield',
								listeners : {
								   specialkey : function(field, e) {
										if (e.getKey() == Ext.EventObject.ENTER)this.ownerCt.ownerCt.ownerCt.doSelectChapter();
									}
								}
							},
							items : [
                '课程','&nbsp;&nbsp;',{ref: '../clesson_id',xtype: 'combo',
                   store:Mt.Chapter.Store.lessonStoreForCombo,hiddenName : 'lesson_id',
                   emptyText: '请选择课程',itemSelector: 'div.search-item',
                   loadingText: '查询中...',width:280,pageSize:Mt.Chapter.Config.PageSize,
                   displayField:'lesson_name',valueField:'lesson_id',
                   mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                     '<tpl for="."><div class="search-item">',
                     '<h3>{lesson_name}</h3>',
                     '</div></tpl>'
                   )
                },'&nbsp;&nbsp;',
                '章节名称','&nbsp;&nbsp;',{ref: '../cchapter_name'},'&nbsp;&nbsp;',
								{
									xtype : 'button',text : '查询',scope: this,
									handler : function() {
										this.doSelectChapter();
									}
								},
								{
									xtype : 'button',text : '重置',scope: this,
									handler : function() {
                    this.topToolbar.clesson_id.setValue("");
                    this.topToolbar.cchapter_name.setValue("");
										this.filter={};
										this.doSelectChapter();
									}
								}]
						}),
						new Ext.Toolbar({
							defaults:{scope: this},
							items : [
								{
									text: '反选',iconCls : 'icon-reverse',
									handler: function(){
										this.onReverseSelect();
									}
								},'-',{
									text : '添加章节',iconCls : 'icon-add',
									handler : function() {
										this.addChapter();
									}
								},'-',{
									text : '修改章节',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
									handler : function() {
										this.updateChapter();
									}
								},'-',{
									text : '删除章节', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
									handler : function() {
										this.deleteChapter();
									}
								},'-',{
									xtype:'tbsplit',text: '导入', iconCls : 'icon-import',
									handler : function() {
										this.importChapter();
									},
									menu: {
										xtype:'menu',plain:true,
										items: [
											{text:'批量导入章节',iconCls : 'icon-import',scope:this,handler:function(){this.importChapter()}}
										]}
								},'-',{
									text : '导出',iconCls : 'icon-export',
									handler : function() {
										this.exportChapter();
									}
								},'-',{
                  text : '下载章节导入模版',iconCls : 'icon-export',
                  handler : function() {
                    this.exportChapterMode();
                  }
                },'-',{
									xtype:'tbsplit',text: '查看章节', ref:'../../tvpView',iconCls : 'icon-updown',
									enableToggle: true, disabled : true,
									handler:function(){this.showChapter()},
									menu: {
										xtype:'menu',plain:true,
										items: [
											{text:'上方',group:'mlayout',checked:false,iconCls:'view-top',scope:this,handler:function(){this.onUpDown(1)}},
											{text:'下方',group:'mlayout',checked:true ,iconCls:'view-bottom',scope:this,handler:function(){this.onUpDown(2)}},
											{text:'左侧',group:'mlayout',checked:false,iconCls:'view-left',scope:this,handler:function(){this.onUpDown(3)}},
											{text:'右侧',group:'mlayout',checked:false,iconCls:'view-right',scope:this,handler:function(){this.onUpDown(4)}},
											{text:'隐藏',group:'mlayout',checked:false,iconCls:'view-hide',scope:this,handler:function(){this.hideChapter();Mt.Chapter.Config.View.IsShow=0;}},'-',
											{text: '固定',ref:'mBind',checked: true,scope:this,checkHandler:function(item, checked){this.onBindGrid(item, checked);Mt.Chapter.Cookie.set('View.IsFix',Mt.Chapter.Config.View.IsFix);}}
										]}
								},'-']}
  					),
            new Ext.Toolbar({
                defaults:{scope: this},
                items : [
                  {
                    text : '切换评论', ref: '../../btnIsComment',iconCls : 'icon-edit',disabled : true,
                    handler : function() {
                      this.setIsComment();
                    }
                  },'-',{
                    text : '切换评分', ref: '../../btnIsScoring',iconCls : 'icon-edit',disabled : true,
                    handler : function() {
                      this.setIsScoring();
                    }
                  },'-',{
                    text : '切换上传文件', ref: '../../btnIsUploadFile',iconCls : 'icon-edit',disabled : true,
                    handler : function() {
                      this.setIsUploadFile();
                    }
                  },'-',{
                    text : '切换广告', ref: '../../btnIsAdvertisement',iconCls : 'icon-edit',disabled : true,
                    handler : function() {
                      this.setIsAdvertisement();
                    }
                  },'-',{
                    text : '导入章节练习', ref: '../../btnPraticeImport',iconCls : 'icon-import',
                    handler : function() {
                      this.importPratice();
                    }
                  },'-',{
                    text : '导出章节练习', ref: '../../btnPraticeImport',iconCls : 'icon-export',
                    handler : function() {
                      this.exportPratice();
                    }
                  },'-',{
                    text : '下载章节练习模版', ref: '../../btnPraticeImport',iconCls : 'icon-export',
                    handler : function() {
                      this.exportPraticeMode();
                    }
                  } ]}
            )
          ]
				},
				bbar: new Ext.PagingToolbar({
					pageSize: Mt.Chapter.Config.PageSize,
					store: Mt.Chapter.Store.chapterStore,
					scope:this,autoShow:true,displayInfo: true,
					displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',
					emptyMsg: "无显示数据",
					listeners:{
						change:function(thisbar,pagedata){
							if (Mt.Chapter.Viewport){
								if (Mt.Chapter.Config.View.IsShow==1){
									Mt.Chapter.View.IsSelectView=1;
								}
								this.ownerCt.hideChapter();
								Mt.Chapter.Config.View.IsShow=0;
							}
						}
					},
					items: [
						{xtype:'label', text: '每页显示'},
						{xtype:'numberfield', value:Mt.Chapter.Config.PageSize,minValue:1,width:35,
							style:'text-align:center',allowBlank: false,
							listeners:
							{
								change:function(Field, newValue, oldValue){
									var num = parseInt(newValue);
									if (isNaN(num) || !num || num<1)
									{
										num = Mt.Chapter.Config.PageSize;
										Field.setValue(num);
									}
									this.ownerCt.pageSize= num;
									Mt.Chapter.Config.PageSize = num;
									this.ownerCt.ownerCt.doSelectChapter();
								},
								specialKey :function(field,e){
									if (e.getKey() == Ext.EventObject.ENTER){
										var num = parseInt(field.getValue());
										if (isNaN(num) || !num || num<1)
										{
											num = Mt.Chapter.Config.PageSize;
										}
										this.ownerCt.pageSize= num;
										Mt.Chapter.Config.PageSize = num;
										this.ownerCt.ownerCt.doSelectChapter();
									}
								}
							}
						},
						{xtype:'label', text: '个'}
					]
				})
			}, config);
			//初始化显示章节列表
			this.doSelectChapter();
			Mt.Chapter.View.Grid.superclass.constructor.call(this, config);
			//创建在Grid里显示的章节信息Tab页
			Mt.Chapter.View.Running.viewTabs=new Mt.Chapter.View.ChapterView.Tabs();
			this.addListener('rowdblclick', this.onRowDoubleClick);
		},
		/**
		 * 行选择器
		 */
		sm : new Ext.grid.CheckboxSelectionModel({
			//handleMouseDown : Ext.emptyFn,
			listeners : {
				selectionchange:function(sm) {
					// 判断删除和更新按钮是否可以激活
					this.grid.btnRemove.setDisabled(sm.getCount() < 1);
          this.grid.btnIsComment.setDisabled(sm.getCount() < 1);
          this.grid.btnIsScoring.setDisabled(sm.getCount() < 1);
          this.grid.btnIsUploadFile.setDisabled(sm.getCount() < 1);
          this.grid.btnIsAdvertisement.setDisabled(sm.getCount() < 1);
          this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
					// this.grid.btnPraticeImport.setDisabled(sm.getCount() != 1);
					this.grid.tvpView.setDisabled(sm.getCount() != 1);
				},
				rowselect: function(sm, rowIndex, record) {
					if (sm.getCount() != 1){
						this.grid.hideChapter();
						Mt.Chapter.Config.View.IsShow=0;
					}else{
						if (Mt.Chapter.View.IsSelectView==1){
							Mt.Chapter.View.IsSelectView=0;
							this.grid.showChapter();
						}
					}
				},
				rowdeselect: function(sm, rowIndex, record) {
					if (sm.getCount() != 1){
						if (Mt.Chapter.Config.View.IsShow==1){
							Mt.Chapter.View.IsSelectView=1;
						}
						this.grid.hideChapter();
						Mt.Chapter.Config.View.IsShow=0;
					}
				}
			}
		}),
		/**
		 * 双击选行
		 */
		onRowDoubleClick:function(grid, rowIndex, e){
			if (!Mt.Chapter.Config.View.IsShow){
				this.sm.selectRow(rowIndex);
				this.showChapter();
				this.tvpView.toggle(true);
			}else{
				this.hideChapter();
				Mt.Chapter.Config.View.IsShow=0;
				this.sm.deselectRow(rowIndex);
				this.tvpView.toggle(false);
			}
		},
		/**
		 * 是否绑定在本窗口上
		 */
		onBindGrid:function(item, checked){
			if (checked){
			   Mt.Chapter.Config.View.IsFix=1;
			}else{
			   Mt.Chapter.Config.View.IsFix=0;
			}
			if (this.getSelectionModel().getSelected()==null){
				Mt.Chapter.Config.View.IsShow=0;
				return ;
			}
			if (Mt.Chapter.Config.View.IsShow==1){
			   this.hideChapter();
			   Mt.Chapter.Config.View.IsShow=0;
			}
			this.showChapter();
		},
		/**
		 * 反选
		 */
		onReverseSelect:function() {
			for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
				if (this.sm.isSelected(i)) {
					this.sm.deselectRow(i);
				}else {
					this.sm.selectRow(i, true);
				}
			}
		},
		/**
		 * 查询符合条件的章节
		 */
		doSelectChapter : function() {
			if (this.topToolbar){
        var clesson_id = this.topToolbar.clesson_id.getValue();
        var cchapter_name = this.topToolbar.cchapter_name.getValue();
        this.filter     ={'lesson_id':clesson_id,'chapter_name':cchapter_name};
			}
			var condition = {'start':0,'limit':Mt.Chapter.Config.PageSize};
			Ext.apply(condition,this.filter);
			ExtServiceChapter.queryPageChapter(condition,function(provider, response) {
				if (response.result&&response.result.data) {
					var result       = new Array();
					result['data']     =response.result.data;
					result['totalCount'] =response.result.totalCount;
					Mt.Chapter.Store.chapterStore.loadData(result);
				} else {
					Mt.Chapter.Store.chapterStore.removeAll();
					Ext.Msg.alert('提示', '无符合条件的章节！');
				}
			});
		},
		/**
		 * 显示章节视图
		 * 显示章节的视图相对章节列表Grid的位置
		 * 1:上方,2:下方,0:隐藏。
		 */
		onUpDown:function(viewDirection){
			Mt.Chapter.Config.View.Direction=viewDirection;
			switch(viewDirection){
				case 1:
					this.ownerCt.north.add(Mt.Chapter.View.Running.viewTabs);
					break;
				case 2:
					this.ownerCt.south.add(Mt.Chapter.View.Running.viewTabs);
					break;
				case 3:
					this.ownerCt.west.add(Mt.Chapter.View.Running.viewTabs);
					break;
				case 4:
					this.ownerCt.east.add(Mt.Chapter.View.Running.viewTabs);
					break;
			}
			Mt.Chapter.Cookie.set('View.Direction',Mt.Chapter.Config.View.Direction);
			if (this.getSelectionModel().getSelected()!=null){
				if ((Mt.Chapter.Config.View.IsFix==0)&&(Mt.Chapter.Config.View.IsShow==1)){
					this.showChapter();
				}
				Mt.Chapter.Config.View.IsFix=1;
				Mt.Chapter.View.Running.chapterGrid.tvpView.menu.mBind.setChecked(true,true);
				Mt.Chapter.Config.View.IsShow=0;
				this.showChapter();
			}
		},
		/**
		 * 显示章节
		 */
		showChapter : function(){
			if (this.getSelectionModel().getSelected()==null){
				Ext.Msg.alert('提示', '请先选择章节！');
				Mt.Chapter.Config.View.IsShow=0;
				this.tvpView.toggle(false);
				return ;
			}
			if (Mt.Chapter.Config.View.IsFix==0){
				if (Mt.Chapter.View.Running.view_window==null){
					Mt.Chapter.View.Running.view_window=new Mt.Chapter.View.ChapterView.Window();
				}
				if (Mt.Chapter.View.Running.view_window.hidden){
					Mt.Chapter.View.Running.view_window.show();
					Mt.Chapter.View.Running.view_window.winTabs.hideTabStripItem(Mt.Chapter.View.Running.view_window.winTabs.tabFix);
					this.updateViewChapter();
					this.tvpView.toggle(true);
					Mt.Chapter.Config.View.IsShow=1;
				}else{
					this.hideChapter();
					Mt.Chapter.Config.View.IsShow=0;
				}
				return;
			}
			switch(Mt.Chapter.Config.View.Direction){
				case 1:
					if (!this.ownerCt.north.items.contains(Mt.Chapter.View.Running.viewTabs)){
						this.ownerCt.north.add(Mt.Chapter.View.Running.viewTabs);
					}
					break;
				case 2:
					if (!this.ownerCt.south.items.contains(Mt.Chapter.View.Running.viewTabs)){
						this.ownerCt.south.add(Mt.Chapter.View.Running.viewTabs);
					}
					break;
				case 3:
					if (!this.ownerCt.west.items.contains(Mt.Chapter.View.Running.viewTabs)){
						this.ownerCt.west.add(Mt.Chapter.View.Running.viewTabs);
					}
					break;
				case 4:
					if (!this.ownerCt.east.items.contains(Mt.Chapter.View.Running.viewTabs)){
						this.ownerCt.east.add(Mt.Chapter.View.Running.viewTabs);
					}
					break;
			}
			this.hideChapter();
			if (Mt.Chapter.Config.View.IsShow==0){
				Mt.Chapter.View.Running.viewTabs.enableCollapse();
				switch(Mt.Chapter.Config.View.Direction){
					case 1:
						this.ownerCt.north.show();
						break;
					case 2:
						this.ownerCt.south.show();
						break;
					case 3:
						this.ownerCt.west.show();
						break;
					case 4:
						this.ownerCt.east.show();
						break;
				}
				this.updateViewChapter();
				this.tvpView.toggle(true);
				Mt.Chapter.Config.View.IsShow=1;
			}else{
				Mt.Chapter.Config.View.IsShow=0;
			}
			this.ownerCt.doLayout();
		},
		/**
		 * 隐藏章节
		 */
		hideChapter : function(){
			this.ownerCt.north.hide();
			this.ownerCt.south.hide();
			this.ownerCt.west.hide();
			this.ownerCt.east.hide();
			if (Mt.Chapter.View.Running.view_window!=null){
				Mt.Chapter.View.Running.view_window.hide();
			}
			this.tvpView.toggle(false);
			this.ownerCt.doLayout();
		},
		/**
		 * 更新当前章节显示信息
		 */
		updateViewChapter : function() {
      Mt.Chapter.View.Running.lattachmentGrid.doSelectLattachment();
      Mt.Chapter.View.Running.lcommentGrid.doSelectLcomment();
      Mt.Chapter.View.Running.lratingGrid.doSelectLrating();
      Mt.Chapter.View.Running.practiceGrid.doSelectPractice();
			if (Mt.Chapter.View.Running.view_window!=null){
				Mt.Chapter.View.Running.view_window.winTabs.tabChapterDetail.update(this.getSelectionModel().getSelected().data);
			}
			Mt.Chapter.View.Running.viewTabs.tabChapterDetail.update(this.getSelectionModel().getSelected().data);
		},
		/**
		 * 新建章节
		 */
		addChapter : function() {
			if (Mt.Chapter.View.Running.edit_window==null){
				Mt.Chapter.View.Running.edit_window=new Mt.Chapter.View.EditWindow();
			}
			Mt.Chapter.View.Running.edit_window.resetBtn.setVisible(false);
			Mt.Chapter.View.Running.edit_window.saveBtn.setText('保 存');
			Mt.Chapter.View.Running.edit_window.setTitle('添加章节');
			Mt.Chapter.View.Running.edit_window.savetype=0;
			Mt.Chapter.View.Running.edit_window.chapter_id.setValue("");
      Mt.Chapter.View.Running.edit_window.head_imageUpload.setValue("");
      switch (Mt.Chapter.Config.OnlineEditor)
      {
          case 1:
              if (CKEDITOR.instances.content) CKEDITOR.instances.content.setData("");
              break
          case 2:
              if (Mt.Chapter.View.EditWindow.KindEditor_content) Mt.Chapter.View.EditWindow.KindEditor_content.html("");
              break
          case 3:
              break
          default:
              if (ue_content)ue_content.setContent("");
      }

			Mt.Chapter.View.Running.edit_window.show();
			Mt.Chapter.View.Running.edit_window.maximize();
		},
		/**
		 * 编辑章节时先获得选中的章节信息
		 */
		updateChapter : function() {
			if (Mt.Chapter.View.Running.edit_window==null){
				Mt.Chapter.View.Running.edit_window=new Mt.Chapter.View.EditWindow();
			}
			Mt.Chapter.View.Running.edit_window.saveBtn.setText('修 改');
			Mt.Chapter.View.Running.edit_window.resetBtn.setVisible(true);
			Mt.Chapter.View.Running.edit_window.setTitle('修改章节');
			Mt.Chapter.View.Running.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
			Mt.Chapter.View.Running.edit_window.savetype=1;
      switch (Mt.Chapter.Config.OnlineEditor)
      {
          case 1:
              if (CKEDITOR.instances.content) CKEDITOR.instances.content.setData(this.getSelectionModel().getSelected().data.content);
              break
          case 2:
              if (Mt.Chapter.View.EditWindow.KindEditor_content) Mt.Chapter.View.EditWindow.KindEditor_content.html(this.getSelectionModel().getSelected().data.content);
              break
          case 3:
              if (xhEditor_content)xhEditor_content.setSource(this.getSelectionModel().getSelected().data.content);
              break
          default:
              if (ue_content)ue_content.setContent(this.getSelectionModel().getSelected().data.content);
      }
      Mt.Chapter.View.Running.edit_window.head_imageUpload.setValue(Mt.Chapter.View.Running.edit_window.head_image.getValue());
			Mt.Chapter.View.Running.edit_window.show();
			Mt.Chapter.View.Running.edit_window.maximize();
		},
		/**
		 * 删除章节
		 */
		deleteChapter : function() {
			Ext.Msg.confirm('提示', '确实要删除所选的章节吗?', this.confirmDeleteChapter,this);
		},
		/**
		 * 确认删除章节
		 */
		confirmDeleteChapter : function(btn) {
			if (btn == 'yes') {
				var del_chapter_ids ="";
				var selectedRows  = this.getSelectionModel().getSelections();
				for ( var flag = 0; flag < selectedRows.length; flag++) {
					del_chapter_ids=del_chapter_ids+selectedRows[flag].data.chapter_id+",";
				}
				ExtServiceChapter.deleteByIds(del_chapter_ids);
				this.doSelectChapter();
				Ext.Msg.alert("提示", "删除成功！");
			}
		},
    /**
     * 切换是否评论
     */
    setIsComment : function() {
      Ext.Msg.confirm('提示', '确实要切换所选的章节的是否评论状态吗?', this.confirmSetIsComment,this);
    },
    /**
     * 确认切换是否评论
     */
    confirmSetIsComment : function(btn) {
      if (btn == 'yes') {
        var chapter_ids = new Array();
        var selectedRows  = this.getSelectionModel().getSelections();
        for ( var flag = 0; flag < selectedRows.length; flag++) {
          var chapter_id = selectedRows[flag].data.chapter_id;
          var isComment = selectedRows[flag].data.isComment;
          var obj = new Array();
          obj.push(chapter_id,isComment);
          chapter_ids.push(obj);
        }
        ExtServiceChapter.setIsComment(chapter_ids);
        this.doSelectChapter();
        Ext.Msg.alert("提示", "切换成功！");
      }
    },
    /**
     * 切换是否评分
     */
    setIsScoring : function() {
      Ext.Msg.confirm('提示', '确实要切换所选的章节的是否评分状态吗?', this.confirmSetIsScoring,this);
    },
    /**
     * 确认切换是否评分
     */
    confirmSetIsScoring : function(btn) {
      if (btn == 'yes') {
        var chapter_ids = new Array();
        var selectedRows  = this.getSelectionModel().getSelections();
        for ( var flag = 0; flag < selectedRows.length; flag++) {
          var chapter_id = selectedRows[flag].data.chapter_id;
          var isScoring = selectedRows[flag].data.isScoring;
          var obj = new Array();
          obj.push(chapter_id,isScoring);
          chapter_ids.push(obj);
        }
        ExtServiceChapter.setIsScoring(chapter_ids);
        this.doSelectChapter();
        Ext.Msg.alert("提示", "切换成功！");
      }
    },
    /**
     * 切换是否上传文件
     */
    setIsUploadFile : function() {
      Ext.Msg.confirm('提示', '确实要切换所选的章节的是否上传文件状态吗?', this.confirmSetIsUploadFile,this);
    },
    /**
     * 确认切换是否上传文件
     */
    confirmSetIsUploadFile : function(btn) {
      if (btn == 'yes') {
        var chapter_ids = new Array();
        var selectedRows  = this.getSelectionModel().getSelections();
        for ( var flag = 0; flag < selectedRows.length; flag++) {
          var chapter_id = selectedRows[flag].data.chapter_id;
          var isUpload_file = selectedRows[flag].data.isUpload_file;
          var obj = new Array();
          obj.push(chapter_id,isUpload_file);
          chapter_ids.push(obj);
        }
        ExtServiceChapter.setIsUploadFile(chapter_ids);
        this.doSelectChapter();
        Ext.Msg.alert("提示", "切换成功！");
      }
    },
    /**
     * 切换是否显示广告
     */
    setIsAdvertisement : function() {
      Ext.Msg.confirm('提示', '确实要切换所选的章节的是否显示广告状态吗?', this.confirmSetIsAdvertisement,this);
    },
    /**
     * 确认切换是否显示广告
     */
    confirmSetIsAdvertisement : function(btn) {
      if (btn == 'yes') {
        var chapter_ids = new Array();
        var selectedRows  = this.getSelectionModel().getSelections();
        for ( var flag = 0; flag < selectedRows.length; flag++) {
          var chapter_id = selectedRows[flag].data.chapter_id;
          var isAdvertisement = selectedRows[flag].data.isAdvertisement;
          var obj = new Array();
          obj.push(chapter_id,isAdvertisement);
          chapter_ids.push(obj);
        }
        ExtServiceChapter.setIsAdvertisement(chapter_ids);
        this.doSelectChapter();
        Ext.Msg.alert("提示", "切换成功！");
      }
    },
		/**
		 * 导出章节
		 */
		exportChapter : function() {
      var chapter_ids ="";
      var selectedRows  = this.getSelectionModel().getSelections();
      for ( var flag = 0; flag < selectedRows.length; flag++) {
        chapter_ids=chapter_ids+selectedRows[flag].data.chapter_id+",";
      }
      var condition = {'chapter_ids':chapter_ids};
      Ext.apply(condition,this.filter);
			ExtServiceChapter.exportChapter(condition,function(provider, response) {
				if (response.result.data) {
					window.open(response.result.data);
				}
			});
		},
    /**
     * 下载章节导入模版
     */
    exportChapterMode : function() {
        window.open("attachment/chapter/chapter.xls");
    },
		/**
		 * 导入章节
		 */
		importChapter : function() {
			if (Mt.Chapter.View.current_uploadWindow==null){
				Mt.Chapter.View.current_uploadWindow=new Mt.Chapter.View.UploadWindow();
			}
			Mt.Chapter.View.current_uploadWindow.show();
		},
    /**
     * 导入章节练习
     */
    importPratice : function() {
      if (Mt.Chapter.View.current_uploadPractireWindow==null){
        Mt.Chapter.View.current_uploadPractireWindow=new Mt.Chapter.View.PracticeUploadWindow();
      }
      // var data = this.getSelectionModel().getSelected().data;

      // Mt.Chapter.View.current_uploadPractireWindow.chapter_id.setValue(data.chapter_id);
      // Mt.Chapter.View.current_uploadPractireWindow.chapter_name.setText('导入章节 '+data.chapter_name+' 的练习题');

      Mt.Chapter.View.current_uploadPractireWindow.show();
    },
    /**
     * 导出章节练习
     */
    exportPratice : function() {
      var chapter_ids ="";
      var selectedRows  = this.getSelectionModel().getSelections();
      for ( var flag = 0; flag < selectedRows.length; flag++) {
        chapter_ids=chapter_ids+selectedRows[flag].data.chapter_id+",";
      }
      var condition = {'chapter_ids':chapter_ids};
      Ext.apply(condition,this.filter);
      ExtServicePractice.exportPractice(condition,function(provider, response) {
        if (response.result.data) {
          window.open(response.result.data);
        }
      });
    },
    /**
     * 下载章节练习导入模版
     */
    exportPraticeMode : function() {
        window.open("attachment/practice/practice.xls");
    }
	}),
  
	/**
	 * 核心内容区
	 */
	Panel:Ext.extend(Ext.form.FormPanel,{
		constructor : function(config) {
			Mt.Chapter.View.Running.chapterGrid=new Mt.Chapter.View.Grid();
			if (Mt.Chapter.Config.View.IsFix==0){
				Mt.Chapter.View.Running.chapterGrid.tvpView.menu.mBind.setChecked(false,true);
			}
			config = Ext.apply({
				region : 'center',layout : 'fit', frame:true,
				items: {
					layout:'border',
					items:[
						Mt.Chapter.View.Running.chapterGrid,
						{region:'north',ref:'north',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true},
						{region:'south',ref:'south',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true,items:[Mt.Chapter.View.Running.viewTabs]},
						{region:'west',ref:'west',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true},
						{region:'east',ref:'east',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true}
					]
				}
			}, config);
			Mt.Chapter.View.Panel.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 当前运行的可视化对象
	 */
	Running:{
		/**
		 * 当前章节Grid对象
		 */
		chapterGrid:null,
    /**
     * 当前会员附件Grid对象
     */
    lattachmentGrid:null,
    /**
     * 当前章节评论Grid对象
     */
    lcommentGrid:null,
    /**
     * 当前章节评分Grid对象
     */
    lratingGrid:null,
    /**
     * 当前练习题Grid对象
     */
    practiceGrid:null,
		/**
		 * 显示章节信息及关联信息列表的Tab页
		 */
		viewTabs:null,
		/**
		 * 当前创建的编辑窗口
		 */
		edit_window:null,
		/**
		 * 当前的显示窗口
		 */
		view_window:null
	}
};
/**
 * Controller:主程序
 */
Ext.onReady(function(){
	Ext.QuickTips.init();
	Ext.state.Manager.setProvider(Mt.Chapter.Cookie);
	Ext.Direct.addProvider(Ext.app.REMOTING_API);
	Mt.Chapter.Init();
	/**
	 * 章节数据模型获取数据Direct调用
	 */
	Mt.Chapter.Store.chapterStore.proxy=new Ext.data.DirectProxy({
		api: {read:ExtServiceChapter.queryPageChapter}
	});
	/**
	 * 章节页面布局
	 */
	Mt.Chapter.Viewport = new Ext.Viewport({
		layout : 'border',
		items : [new Mt.Chapter.View.Panel()]
	});
	Mt.Chapter.Viewport.doLayout();
	setTimeout(function(){
		Ext.get('loading').remove();
		Ext.get('loading-mask').fadeOut({
			remove:true
		});
	}, 250);
});